JavaScript for…in vs for

2018-12-31 09:57发布

Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?

Let's say we have an array of associative arrays:

var myArray = [{'key': 'value'}, {'key': 'value1'}];

So we can iterate:

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

And:

for (var i in myArray)

I don't see a big difference. Are there any performance issues?

标签: javascript
23条回答
步步皆殇っ
2楼-- · 2018-12-31 10:33

Use the Array().forEach loop to take advantage of parallelism

查看更多
不流泪的眼
3楼-- · 2018-12-31 10:37

A shorter and best code according to jsperf is

keys  = Object.keys(obj);
for (var i = keys.length; i--;){
   value = obj[keys[i]];// or other action
}
查看更多
琉璃瓶的回忆
4楼-- · 2018-12-31 10:39

With for (var i in myArray) you can loop over objects too, i will contain the key name and you can access the property via myArray[i]. Additionaly, any methods you will have added to the object will be included in the loop, too, i.e., if you use any external framework like jQuery or prototype, or if you add methods to object prototypes directly, at one point i will point to those methods.

查看更多
荒废的爱情
5楼-- · 2018-12-31 10:39

Watch out!

If you have several script tags and your're searching an information in tag attributes for example, you have to use .length property with a for loop because it isn't a simple array but an HTMLCollection object.

https://developer.mozilla.org/en/DOM/HTMLCollection

If you use the foreach statement for(var i in yourList) it will return proterties and methods of the HTMLCollection in most browsers!

var scriptTags = document.getElementsByTagName("script");

for(var i = 0; i < scriptTags.length; i++)
alert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)

for(var i in scriptTags)
alert(i); // Will print "length", "item" and "namedItem" in addition to your elements!

Even if getElementsByTagName should return a NodeList, most browser are returning an HTMLCollection: https://developer.mozilla.org/en/DOM/document.getElementsByTagName

查看更多
只靠听说
6楼-- · 2018-12-31 10:41

Updated answer for 2012 current version of all major browsers - Chrome, Firefox, IE9, Safari and Opera support ES5's native array.forEach.

Unless you have some reason to support IE8 natively (keeping in mind ES5-shim or Chrome frame can be provided to these users, which will provide a proper JS environment), it's cleaner to simply use the language's proper syntax:

myArray.forEach(function(item, index) {
    console.log(item, index);
});

Full documentation for array.forEach() is at MDN.

查看更多
登录 后发表回答