Explanation for in loop javascript

大憨熊 提交于 2019-12-01 08:24:18
Mritunjay

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    

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!