JavaScript for...in vs for

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?


The choice should be based on the which idiom is best understood.

An array is iterated using:

for (var i = 0; i < a.length; i++)
   //do stuff with a[i]

An object being used as an associative array is iterated using:

for (var key in o)
  //do stuff with o[key]

Unless you have earth shattering reasons, stick to the established pattern of usage.


Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in statement.

If you use for in to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.

Everything but the properties can be filtered out with .hasOwnProperty . This code sample does what you probably wanted originally:

for (var name in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, name)) {
        // DO STUFF
    }
}

FYI - jQuery Users


jQuery's each(callback) method uses for( ; ; ) loop by default, and will use for( in ) only if the length is undefined .

Therefore, I would say it is safe to assume the correct order when using this function.

Example :

$(['a','b','c']).each(function() {
    alert(this);
});
//Outputs "a" then "b" then "c"

The downside of using this is that if you're doing some non UI logic, your functions will be less portable to other frameworks. The each() function is probably best reserved for use with jQuery selectors and for( ; ; ) might be advisable otherwise.


链接地址: http://www.djcxy.com/p/24524.html

上一篇: 如何使简单的PHP的foreach相当于Javascript?

下一篇: JavaScript for ... in和vs for