使用数组值作为数组名称

时间:2015-05-05 12:29:59

标签: javascript jquery arrays

我正在使用5个数组和2个FOR循环在页面上创建一组div,但内部循环不能正常工作并且正在为某些项目返回UNDEFINED。我知道原因是因为它使用的是实际颜色名称的长度[red(3),orange(6),green(5),blue(4)]而不是这些数组的实际长度。

如何使用第二个数组名称动态地使用第一个数组(颜色)中的实际颜色名称。我错过了什么?

var colours = ["red", "orange", "green", "blue"];
var red = ["item1", "item2", "item3", "item4"];
var orange = ["item5", "item6"];
var green = ["item7", "item8", "item9", "item10", "item11"];
var blue = ["item12"];
//generate coloured boxes
for (var i = 0; i < colours.length; i++) {
    var colour = colours[i];
    $("<div class='box " + colour + "' id='" + colour + "'>").appendTo('#boxes');
    //generate items in boxes
    for (var j = 0; j < colours[i].length; j++) {
        $("<div id='" + red[j] + "'>" + red[j] + "</div>").appendTo("#" + colours[i]);
    }
    $("</div>").appendTo('#boxes');
}

1 个答案:

答案 0 :(得分:0)

这是糟糕的编程;您可能需要最终使用eval

var colours = ["red", "orange", "green", "blue"];
var red = ["item1", "item2", "item3", "item4"];
var orange = ["item5", "item6"];
var green = ["item7", "item8", "item9", "item10", "item11"];
var blue = ["item12"];

如果你创建一个颜色名称及其项目的字典(并使用jQuery函数来创建元素)会更好:

var colours = ["red", "orange", "green", "blue"];
var colourValues = {
    red: ["item1", "item2", "item3", "item4"],
    orange: ["item5", "item6"],
    green: ["item7", "item8", "item9", "item10", "item11"],
    blue: ["item12"]
};
for (var i = 0; i < colours.length; i++) {
    var colour = colours[i];
    var colourValue = colourValues[colour];
    var $box = $("<div></div>", { "class": "box " + colour, id: colour }).appendTo("#boxes");
    for (var j = 0; j < colourValue.length; j++) {
        $("<div></div>", { id: colourValue[j] }).text(colourValue[j]).appendTo($box);
    }
}