Let's say I have a single element array ["someStringHere"] (I don't know in advance what the string will be) and I want to access the string so that my function returns the string and not the array, how could I do so without using an indexer (ex: array[0])?
In other words, it would be as if I could delete the brackets so that I just had the string.
Every object has a toString method. You could go about using this method, though it's confusing why you'd want to. Another option is the join method.
var someArr = ['some string here'];
console.log(someArr.toString());
console.log(someArr.join());
According to MDN:
The Array object overrides the toString method of Object. For Array
objects, the toString method joins the array and returns one string
containing each array element separated by commas.
See here for specifics.
Amusingly, that works just by forcing it to a string type:
var someArr = ['some string here'];
console.log( "" + someArr );
And one more for the road:
someArr.forEach (function (s) { console.log(s) });
Related
In JavaScript, you can have objects, like this:
var a = { foo: 12, bar: 34 };
Or arrays with key (named) indexes, like this:
var b = [];
b['foo'] = 56;
b['bar'] = 78;
They're somewhat similar, but obviously not the same.
Now the strange thing is, JSON.stringify doesn't seem to take the array. No errors or anything, JSON.stringify(b) just results in [].
See this jsfiddle example. Am I doing something wrong, or do I just misunderstand how arrays work?
Javascript doesn't support Associative arrays (Like PHP).
var b = []; Declaring explicitly an array, when you are trying to create an Object.
Arrays in Javascript can only contain the Index approach of Arrays, while Objects are more of
Associative arrays.
If you change var b = []; to var b = {}; it will solve the problem.
var b = {} Declaring explicitly an Object.
Javascript arrays are objects. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object for details.
Note: if you supply a non-integer value to the array operator in the
code above, a property will be created in the object representing the
array, instead of an array element.
JSON supports only a subset of Javascript. See http://www.json.org/ for details.
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
A Javascript array that has properties created in the underlying object does not fit into either of these structures because it has both a collection of name/value pairs and an ordered list of values, so there is no simple way to represent such an object directly in JSON.
The JSON.stringify method is defined in the ECMAScript specification. For example, see http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3.
While there are many details, the bit that is relevant here is how object values are stringified:
If Type(value) is Object, and IsCallable(value) is false
If the [[Class]] internal property of value is "Array" then Return the result of calling the abstract operation JA with argument value.
Else, return the result of calling the abstract operation JO with argument value.
Given your array, despite the addition of parameters to the underlying object, the result is of stringifying the ordered set of array elements, not the underlying object.
There is nothing wrong about adding parameters to an array object, but they are not part of the array and functions or methods that handle arrays might ignore them or deal with them arbitrarily. You have seen that JSON.stringify ignores the additional parameters. Other functions might do otherwise - you will have to find out in each case.
While it is not wrong, it will probably be easier to understand if you do not add properties to array objects. If you want to add properties, start with a non-array object.
Rather than:
var b = [];
b['foo'] = 56;
b['bar'] = 78;
You might use:
var b = {};
b['foo'] = 56;
b['bar'] = 78;
This snap is from IE explorer. See the array is still blank.
Actually the way of inserting the elements to the array is :
1. Use push()
2. insert the elements in the array during declaration
If you want to stringify the array you have to have the data inside the array.
So, now you want to stringify the key value pairs so you have to pass the object as the argument of JSON.stringify() as follows:
var test = {}; // Object
test['a'] = 'test';
test['b'] = []; // Array
test['b'].push('item');
test['b'].push('item2');
test['b'].push('item3');
var json = JSON.stringify(test);
alert(json);
Solution to your problem now:
Note: Console of Google Chrome is giving different result, which is a bug in Google Chrome.
var hello = 'hello';
Array.prototype.unshift.call(hello, '11') // gives error
Array.prototype.join.call(hello, ', ') // works, why??
can someone explain to me why .join works and why .unshift doesn't
Because strings are immutable, and unshift tries to assign to an index (property) of the string, as in
"hello"[4] = '1'
Reference: http://www.ecma-international.org/ecma-262/6.0/#sec-string-exotic-objects:
A String object is an exotic object that encapsulates a String value and exposes virtual integer indexed data properties corresponding to the individual code unit elements of the String value. Exotic String objects always have a data property named "length" whose value is the number of code unit elements in the encapsulated String value. Both the code unit data properties and the "length" property are non-writable and non-configurable.
join doesn't assign anything and only reads properties, therefore it works with any object that has .length.
Try this:
String.prototype.unshift = function(el) {
let arr = [this];
arr.unshift(el);
return arr.join("");
}
var s = "BCD";
s = s.unshift("A");
console.log(s); // ABCD
Unintentionally, In my project I had used the following code and I was surprised to see that is working:
HTML
<span id="output"></span>
Javascript
var myObject = {
'a': '----First---',
'b': '----Second---',
'c': '----Third----'
};
var myArray = ['a'];
// First Case
output.innerHTML = myObject[myArray];
var myArray2 = ['b'];
// Second Case
output.innerHTML += myObject[myArray2];
var myArray3 = ['a', 'b'];
// Third Case
output.innerHTML += myObject[myArray3];
Output
----First-------Second---undefined
Jsbin Link: http://jsbin.com/godilosifu/1/edit?html,js,output
I am directly accessing array reference within Object which should be undefined in all the cases but strangely When array is of Size 1, it always gets the first element and use that as the object key.
I just want to know what is this concept called and why is this happening ?
Because the property name has to be a string, it is type cast into one using the toString() method. The reason that your third example is undefined is that ['a', 'b'].toString() equals 'a,b', which is not a property in your object.
Property names
Property names must be strings. This means that non-string objects
cannot be used as keys in the object. Any non-string object, including
a number, is typecasted into a string via the toString method.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Worth noting is that in ECMAScript 6, there is a new collection type called Map, which allows you to use any object as a key without type coercion.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
When you pass the array to the object as a Key, it is calling toString() on it. This is because all Keys in Javascript are Strings.
['a'].toString() is "a"
myObject['a'] is "----First----"
See: Keys in Javascript objects can only be strings?
It's auto-casting. In Javascript, only strings can be indexes into an object's properties. myObject is not an array, it's an object. Even though you're using the brackets to access it's properties, it is not the same meaning as brackets used on an array object.
Due to object properties only being allowed to be named by strings, the compiler auto-casts your array to a string (essentially calling it's native toString() function, which for an array, joins all the elements with a comma).
So when you pass your array to the object's property accessor/index, it does this:
myArray1 ==> "a";
myArray2 ==> "b";
myArray3 ==> "a" + "," + "b" ===> "a,b";
So I've tried to use the map() method as follows:
words = ["One", "Two"];
words = words.map(function(currentValue)
{
alert(currentValue[0]);//Output: O Then: T
currentValue[0] = "A";
alert(currentValue[0]);//Output: O Then: T
return currentValue;
});
Why is it that currentValue[0] is not getting assigned the value "A"?!?
Your attempting to assign to a string at a specific position via its index, this is not possible as Strings are immutable. If you want to change a string you need to create a new one.
As Alex K correctly points out, strings are immutable and you cannot modify them.
Since you are using a .map(), the thing to do here is just construct a new string and return that:
var words = ["One", "Two"];
words = words.map(function (currentValue) {
return "A" + currentValue.substring(1);
});
console.log(words); // outputs ["Ane", "Awo"];
As a rule of thumb, you should not try to use .map() to modify existing values. The purpose of .map() is to produce a new set of values, and leave the original ones untouched.
In JavaScript String is the primitive type, so you cannot mutate it.
String , Number , Boolean, Null, Undefined, Symbol (new in ECMAScript 6) are primitive types.
I want to add prototype function in string object. I working with it but it is not uppercase the string value. Fiddle
String.prototype.myUcase=function()
{
return this.toUpperCase();
}
In javascript String is not mutable. So, when you do this.toUpperCase() it does not change the current string. Instead, it creates a new string with the uppercased letters in it.
If you want your example to work, you can do (as suggested by elclanrs in the comments)
fruits = fruits.myUcase();