I tried this code in the address bar:
javascript: alert({} + [])
The result is: [object Object].
javascript: alert(typeof ({} + []))
The result is: string.
Can somebody explain to me what's going on?
Arrays are best to use when the elements are numbers. objects are best to use when the elements strings (text). 2.
An array can be inserted into the object with push() function, below examples illustrate the above approach: Example 1: Javascript.
In summary, the addition of arrays causes them to be coerced into strings, which does that by joining the elements of the arrays in a comma-separated string and then string-concatenating the joined strings.
When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
The concatenation operator (+) concatenates two string values together. If you give it things that are not string values, then it calls the .toString()
method on them first.
In response to the comment below, "Yes it does!"
Object.prototype.toString = function () { return "a"; };
Array.prototype.toString = function () { return "b"; };
var foo = {} + [];
alert(foo); // alerts 'ab'
Without the above modifications to the prototypes, if you have alert({} + [])
then you are taking {}.toString()
(which is "[Object object]"
) and [].toString()
(which is ""
as the array is empty), then concatenating them (which is still "[Object object]"
). This is a string and typeof
will tell you that it is a string.
It looks like because the +
operator is not defined to accept arguments as one []
and one {}
, it basically converts both to strings (makes more sense than trying to cast them into numbers) and then applies +
as the concatenation operator.
Edit: In response to the changed question, I think they are still being converted into a string first. Here's a session in spidermonkey where I tried it out:
js> x=[]+{}
[object Object]
js> z=x[0]
[
js> x.length
15
js> x=[]+{}
[object Object]
js> x.length
15
js> x[0]
[
js> x[1]
o
js> for (var i=0;i<x.length;i++) {print(x[i]);}
[
o
b
j
e
c
t
O
b
j
e
c
t
]
js> typeof(x)
string
js> print(x)
[object Object]
What is happening is that the result of {}+[]
is a string, but not en empty string. Rather it is the string "[object Object]".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With