对循环内javascript的解释
我很难理解in循环的工作方式对循环内javascript的解释,javascript,loops,for-in-loop,Javascript,Loops,For In Loop,我很难理解in循环的工作方式 function createSimpleNode(name, options, text) { var node = document.createElement(name); for (var o in options) { node.setAttribute(o, options[o]); } if (text) { n
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;
}
这是一个很好的例子。它迭代对象的属性(options
,在本例中),并允许您使用[]
操作符在每次迭代中访问所述属性
在您的示例中,您迭代选项
属性,并将它们全部设置为节点的属性
提供了使用每个值和键迭代对象或数组的方法
它可以应用于对象
或数组
对于一个对象
对于对象,它将对象中的每个键作为ITER变量提供。
使用此变量,您可以从对象中获得相应的值
var options = {a:1,b:2};
for (var key in options) {
console.log(o,options[key]);
}
将迭代选项
对象并打印每个键及其值
a 1 //first key is a and options["a"] is 1
b 2 //first key is a and options["b"] is 2
对于数组
对于数组,它将数组中的每个索引作为ITER变量提供。
使用此变量,您可以从数组中获得相应的元素
var options = ["a","b"];
for (var index in options) {
console.log(index,options[index]);
}
将迭代选项
数组,并在给定索引上打印每个索引
和元素。输出将是:-
0 a //first index is a and options[0] is a
1 b //second index is a and options[1] is b
对于只对集合进行In-迭代,它将从列表中提取第一个类型,并在下面的代码块中使用它。在选项[o]中使用o将永远不会设置,因为它不是集合中的索引。也许看看我更新的答案,比如对象和数组