質問

What are some of the practical for in loop use cases in JavaScript? They're bad for arrays since they ignore undefined keys and return numerable properties of the array object. I've never seen them used in any production code. Have they been all but deprecated by developers?

役に立ちましたか?

解決

They are best for iterating over Javascript or JSON objects, like {"foo":bar,"baz":boo}, but not for arrays, see more here for more info about that.

They are best done like this:

var obj={"foo":bar,"baz":boo}
for(var key in obj){
   //hasOwnProperty ensures that it exists and bad stuff doesn't happen with deleted properties
   if(obj.hasOwnProperty(key)){
       obj[key].doSomething();
   }
}

Douglas Crockford has a very good page on this here. For arrays, they should never be used, but they are very useful for objects, especially if you don't know what order the keys will be in, or what keys will be there. For arrays, just do this

for(var i=0;i<array.length;i++){
//do some stuff
}

他のヒント

It is useful for iterating objects where the iteration is not dependent on order. It is useful in a few ways.

The variable used in the for in statement is the key to the current value.

The shorthand notation can save a few characters in the .js file.

It can be more readable.

The MDN says:

Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

You may also check Exploring JavaScript for-in loops

var str = "hello!", spreadOut = "";

for (var index in str) {
    (index > 0) && (spreadOut += " ")
    spreadOut += str[index];
}

spreadOut; //"h e l l o !"

You may refer this thread where CMS has explained it:

The purpose of the for-in statement is to enumerate over object properties, this statement will go up in the prototype chain, enumerating also inherited properties, thing that sometimes is not desired.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top