Explanation for javascript loop

I am having trouble understanding how the loop for .

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; 
}

      

+3


source to share


2 answers


For loop, allows you to iterate over an object or array with each value and key.

It can be applied to object

or Array

.

For object

For an object, it gives each key

in the object as ITER variable.

Using this variable, you can get the corresponding value from the object.

var options = {a:1,b:2};

for (var key in options) { 
    console.log(o,options[key]);
}

      

Will walk through the object options

and print each one key

and its 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 ITER variable.

Using this variable, you can get the corresponding element from the array.

var options = ["a","b"];

for (var index in options) { 
    console.log(index,options[index]);
}

      

Iterates over the array options

and prints each index

and element at the given index. The 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    

      

+4


source


This is for..in loop . it iterates over the properties of the object ( options

in this case) and allows you to access the specified property on each iteration using a statement []

.



In your example, you iterate over the properties options

and set them as attributes node

.

+1


source







All Articles