如何修复这个简单的Javascript'for loop'?

时间:2012-11-23 09:21:22

标签: javascript

我有很多Javascript对象。

我想要一个简单的for循环' (在JS中)打印出每个对象中的键:值对。

我已经展示了我在下面做过的事情(这里是in a FIDDLE),但变量' thisvar'没有工作。

我显然错过了一些非常简单的事情 - 你能指出它是什么吗?

由于

// declare objects
var variant1 = {};
var variant2 = {};

variant1['a'] = 'apple';
variant1['b'] = 'orange';
variant1['c'] = 'pear';

variant2['a'] = 'red';
variant2['b'] = 'green';
variant2['c'] = 'blue';

// run through each object
for (i=1; i<3; i++){
    var thisvar = variant+i;
    for(var newindex in thisvar) {
        var name = newindex;
        var contents = thisvar[newindex];
        alert(name+'='+contents);
    }
}

3 个答案:

答案 0 :(得分:3)

// declare objects
var container = {
    variant1: {}
    variant2: {}
}

container.variant1['a'] = 'apple';
container.variant1['b'] = 'orange';
container.variant1['c'] = 'pear';

container.variant2['a'] = 'red';
container.variant2['b'] = 'green';
container.variant2['c'] = 'blue';

// run through each object
for (var i = 1; i < 3; i++){
    for (prop in container["variant"+i]){
         if (variant.hasOwnProperty(prop)){
            alert(prop+'='+var[prop]);
         }
    }
}

正如下面的评论所指出的,如果你想在数字上迭代属性,你最好只使用一个数组:

// declare objects
var variants = [{},{}];

variants[0]['a'] = 'apple';
variants[0]['b'] = 'orange';
variants[0]['c'] = 'pear';

variants[1]['a'] = 'red';
variants[1]['b'] = 'green';
variants[1]['c'] = 'blue';

// run through each object
for (var i = 0; i < 2; i++){
    for (prop in variants[i]){
         if (variant.hasOwnProperty(prop)){
            alert(prop+'='+var[prop]);
         }
    }
}

答案 1 :(得分:1)

试试这个:

var variant1 = new Object();
variant1['a'] = 'apple';
variant1['b'] = 'orange';
variant1['c'] = 'pear';
var variant2 = new Object();
variant2['a'] = 'red';
variant2['b'] = 'green';
variant2['c'] = 'blue';


for (i=1; i<3; i++){
var thisvar ;
eval( 'thisvar = variant'+i);
    for(var newindex in thisvar) {
        var name = newindex;
        var contents = thisvar[newindex];
        alert(name+'='+contents);
    }
}

答案 2 :(得分:1)

如果您只想检查对象属性,只需执行

即可
alert(JSON.stringify(container))