Javascript - 使用数组作为对象名称,然后使用循环获取属性

时间:2014-10-19 09:26:17

标签: javascript jquery

疯狂尝试这样做,所以我想我会得到帮助。我有一个像这样的数组:

OBJECTS = ["mainmenu","mainviewer","mainsearch"];

这些都是这样的对象:

mainmenu = {width:250,height:250,backgroundcolor:red};
mainviewer = {width:250,height:250,backgroundcolor:green};
mainsearch = {width:250,height:250,backgroundcolor:blue};

现在它的关键......我只是想尝试这样的属性:

for (var item in OBJECTS) {
    var name = OBJECTS[item];
    console.log("the width of "+name+" is "+name.width);
}

控制台会回复给我:

the width of mainmenu is undefined

任何帮助都非常感谢...

2 个答案:

答案 0 :(得分:1)

您的OBJECTS数组是一个字符串数组。它不是一个对象数组。

也许你的意思是:

var mainmenu = {width:250,height:250,backgroundcolor:"red"};
var mainviewer = {width:250,height:250,backgroundcolor:"green"};
var mainsearch = {width:250,height:250,backgroundcolor:"blue"};

var objects = [mainmenu, mainviewer, mainsearch];

仅供参考,我还必须在颜色名称周围加上引号,因为red之类的符号未定义。


而且,如果你想用名字迭代它,你可以这样做:

var mainmenu = {name: "mainmenu", width:250,height:250,backgroundcolor:"red"};
var mainviewer = {name:"mainview", width:250,height:250,backgroundcolor:"green"};
var mainsearch = {name: "mainsearch", width:250,height:250,backgroundcolor:"blue"};

var objects = [mainmenu, mainviewer, mainsearch];

objects.forEach(function(item) {
    log("the width of "+item.name+" is "+item.width);
});

或传统的for循环:

for (var i = 0; i < objects.length; i++) {
    var item = objects[i];
    console.log("the width of "+item.name+" is "+item.width);
});

工作演示:http://jsfiddle.net/jfriend00/abwgjed2/


注意:使用语法for (item in objects)迭代数组是个坏主意。这将迭代item对象的所有属性,而不仅仅是数组元素。如果使用ES5 / ES6 polyfill,可能会有一些额外的可枚举属性将显示在for (item in objects)迭代中。使用.forEach()for (var i = 0; i < objects.length; i++)

答案 1 :(得分:0)

这里是demo

var OBJECTS = 
    {
      mainmenu : {width:250,height:250,backgroundcolor:'red'},
      mainviewer : {width:250,height:250,backgroundcolor:'green'},
      mainsearch : {width:250,height:250,backgroundcolor:'blue'}
  }

for (var item in OBJECTS) {
    var name = OBJECTS[item];
    console.log("the width of "+item+" is "+name.width);
}