1

我有许多 Javascript 对象。

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

我在下面展示了我所做的(这里是在 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);
    }
}

​</p>

4

3 回答 3

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]);
         }
    }
}
于 2012-11-23T09:22:58.060 回答
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);
    }
}
于 2012-11-23T09:23:14.647 回答
1

如果您只想检查对象属性,您可以简单地做

alert(JSON.stringify(container))
于 2012-11-23T09:34:34.650 回答