Version 1:
var spamfoo = new Array();
spamfoo.push(['name', 'url']);
spamfoo.push(['dog', 'cat']);
alert(spamfoo);
// Alerts: name,url,dog,cat
alert(spamfoo.length);
// Alerts: 2
// ??? (shouldn't this be 4?)
Version 2:
var spamfoo = new Array();
spamfoo.push(['name', 'url']);
spamfoo = spamfoo + ['dog', 'cat'];
alert(spamfoo);
// Alerts: name,url,dog,cat
alert(spamfoo.length);
// Alerts: 15
// ??? (this one I wasn't sure about anyways because I didn't know if you could add an array)
How is this possible? Doesn’t ['value', 'value'] make an array and doesn’t?
The answer is that
my_array.lengthdoes work but you’re missing some of the implicit type conversions that are happening and whatpush()does.In the first example, you are creating a multidimensional array. Technically it’s an array of arrays rather than a true multidimensional array. The first code snippet creates this array of arrays:
which is of length 2 so that result is correct.
The second example’s use of the concatenation operator
+convertsspamfooto a string, which means thatlengthis now returning the string length. The string length is 15 so this too is correct.You might want to add this line to your examples:
If so you’ll see the first example displays
objectand the second displaysstring.