循环JavaScript的说明 [英] Explanation for in loop javascript

查看:85
本文介绍了循环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.

它可以应用于objectArray.

对于一个对象,它将对象中的每个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆