Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation for in loop javascript

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; 
}
like image 415
Ryner Avatar asked Feb 04 '26 05:02

Ryner


2 Answers

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    
like image 67
Mritunjay Avatar answered Feb 06 '26 17:02

Mritunjay


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.

like image 33
Mureinik Avatar answered Feb 06 '26 19:02

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!