循环JavaScript的说明 [英] Explanation for in loop javascript
问题描述
我无法理解此 for in 循环的工作方式.
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;
}
推荐答案
The For in loop gives a way to iterate over an object or array with each value and key.
它可以应用于object
或Array
.
对于一个对象,它将对象中的每个key
都指定为ITER variable.
.使用此变量,您可以从对象中获取相应的值.
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]);
}
将遍历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
对于数组
对于数组,它将数组中的每个index
都指定为ITER variable.
.使用此变量,您可以从数组中获取相应的元素.
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]);
}
将遍历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
这篇关于循环JavaScript的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!