JavasScript: Why does my_array.length not work?
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.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
.
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
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
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);
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.
精彩评论