问题
I'm having trouble understanding the way this for in loop works.
function createSimpleNode(name, options, text) {
var node = document.createElement(name);
for (var o in options) {
node.setAttribute(o, options[o]);
}
if (text) {
node.innerHTML = text;
}
return node;
}
回答1:
The For in loop gives a way to iterate over an object or array with each value and key.
It can be applied over an object
or Array
.
For an Object
For an object it gives each key
in the object as the ITER variable.
Using this variable you can get the corresponding value from object.
var options = {a:1,b:2};
for (var key in options) {
console.log(o,options[key]);
}
Will Iterate over the options
object and print each key
and it's value.
a 1 //first key is a and options["a"] is 1
b 2 //first key is a and options["b"] is 2
For an Array
For an array it gives each index
in the array as the ITER variable.
Using this variable you can get the corresponding element from array.
var options = ["a","b"];
for (var index in options) {
console.log(index,options[index]);
}
Will Iterate over the options
array and print each index
and element on given index. Output will be:-
0 a //first index is a and options[0] is a
1 b //second index is a and options[1] is b
回答2:
This is a for..in loop. it iterates over the properties of an object (options
, in this case), and allows you access the said property in each iteration using the []
operator.
In your example, you iterate over options
properties, and set them all as attributes of node
.
来源:https://stackoverflow.com/questions/27752659/explanation-for-in-loop-javascript