tags:

views:

66

answers:

5

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?

+3  A: 

The answer is that my_array.length does work but you're missing some of the implicit type conversions that are happening and what push() 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:

[
  ["name", "url"],
  ["dog", "cat"]
]

which is of length 2 so that result is correct.

The second example's use of the concatenation operator + converts spamfoo to a string, which means that length is 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:

alert(typeof spamfoo);

If so you'll see the first example displays object and the second displays string.

cletus
+4  A: 

For the first part, you'll get a nested array (2x2), hence spamfoo.length returns 2. It looks like:

[
    ['name', 'url'],
    ['dog', 'cat']
]

The second part, is as cletus said above, is a type casting into string

K Prime
+1. Agree. After pushing twice, the container will contain 2 things. This should be accepted answer.
RocketSurgeon
Yes I agree. Basically your inserting another array object into your array.
samer
A: 

Do it like this

var spamfoo = new Array(); var x=["name", "url","d"]; spamfoo.push("name", "url","d"); spamfoo.push("xxxx"); //spamfoo.push('dog');

// Alerts: name,url,dog,cat alert(spamfoo.length);

samer
+1  A: 

You want to flatten those arrays before pushing them. Try this:

var spamfoo = [];
Array.prototype.push.apply(spamfoo, ["name", "url"]);
Array.prototype.push.apply(spamfoo, ["dog", "cat"]);
alert(spamfoo.length); // alerts 4
darkporter
A: 

The first one I posted is wrong. There is the extra "var x=xxxxxxxxx"

This is the correct one.

var spamfoo = new Array();

spamfoo.push("name", "url","d");
spamfoo.push("xxxx");
//spamfoo.push('dog');

// Alerts: name,url,dog,cat
alert(spamfoo.length);

K prime is right.. This is a mistake spamfoo.push(['name', 'url']); spamfoo.push(['dog', 'cat']);

Your inserting an array into an array object.

samer