-->

Looping through empty javascript array returns arr

2019-04-13 04:07发布

问题:

I noticed that in my javascript, if I create an empty array, loop through it as an associative array, and print out the contents, it returns what looks like functions from the Array Object class itself. Here is my code:

var test = new Array();
for(var i in test){
    document.write(i + " " + test[i] + "<br>");
}
alert(test.length); // this returns 0

The above code prints the following (I'm omitting some of the output since it's kind of long)

$family function (){return u; }
$constructor function Array() { [native code] }
pop function pop() { [native code] }
push function push() { [native code] }
reverse function reverse() { [native code] }
shift function shift() { [native code] }
sort function sort() { [native code] }
splice function splice() { [native code] }
unshift function unshift() { [native code] }
concat function concat() { [native code] }
join function join() { [native code] }
slice function slice() { [native code] }
indexOf function indexOf() { [native code] }
etc...

I noticed that if I loop through the array using a for loop ie:

for(var i = 0; i < test.length; i++)

the browser doesn't print out anything (which is what should happen)

Can anyone explain why I'm getting a bunch of functions from an empty array when I loop through it the other way? In case it matters, I'm using mootools v1.3. Thanks in advance.

回答1:

Get rid of whatever extends Array.prototype. Extending the prototype of default types like Array or Object is bad and causes problems like that.

The easy way to circumvent issues while keeping the prototype extensions is adding a if(!test.hasOwnProperty(i)) continue; check. (obj.hasOwnProperty(key) is true if the property is on the object itself and not only somewhere in its prototype chain)

Besides that, you shouldn't use for..in loops when iterating over arrays - use for(var i = 0; i < array.length; i++) in this case.



回答2:

A little late to the party, but I found this while trying to find a way to do this. This is what I came up with.

function createArrayOfEmptyObjects(size) {
    return Array.apply(0, new Array(size).map(function(){return {};});
}

It will, as its name implies, create an array of empty objects up to a provided size.