Looping through empty javascript array returns array object functions

廉价感情. 提交于 2019-12-04 16:47:22

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!