我以为我做的正确,但这可能是一个完全的菜鸟错误。

这是我的JSON数据

{
"rows": {
    "row1": {
        "divs": 7,
        "offset": 0,
        "colors": {
            "color1": "#003366",
            "color2": "#336699",
            "color3": "#3366CC",
            "color4": "#003399",
            "color5": "#000099",
            "color6": "#0000CC",
            "color7": "#000066"
        }
    },
    "row2": {
        "divs": 8,
        "offset": 11,
        "colors": {
            "color1": "#006666",
            "color2": "#006699",
            "color3": "#0099CC",
            "color4": "#0066CC",
            "color5": "#0033CC",
            "color6": "#0000FF",
            "color7": "#3333FF",
            "color8": "#333399"
        }
    },
    "row3": {
        "divs": 9,
        "offset": 22,
        "colors": {
            "color1": "#669999",
            "color2": "#009999",
            "color3": "#33CCCC",
            "color4": "#00CCFF",
            "color5": "#0099FF",
            "color6": "#0066FF",
            "color7": "#3366FF",
            "color8": "#3333CC",
            "color9": "#666699"
        }
    }
}
}

我将其保存到文件中并推入这样的数组中
var colorPicker = []

$(function () {
$.getJSON("js/json/colorPicker.json", function (data) {
    colorPicker.push(data)
});
})

现在,我正在尝试访问此数组。
我可以通过colorPicker[0]进入它
那将返回整个对象。
Object {rows: Object}

当我执行colorPicker[0].rows时,它将返回3行
Object {row1: Object, row2: Object, row3: Object}

但是,当我执行colorPicker[0][1]时,不应该只给我一行吗?
我不断变得不确定。

当我执行colorPicker[0].rows.row1时,我可以从那里访问我的值。但是,如果我想为每个循环使用a,那么像colorPicker[0][1].divs这样的事情会更容易些,会吗?我要解决这个错误吗?

最佳答案

由于它是一个对象,因此不能通过索引0,1,2进行索引,而是需要提供键的名称,因此,如果要遍历对象内的所有键,则可以执行以下操作:

$.each(colorPicker[0]['rows'], function(key){
    console.log(colorPicker[0]['rows'][key]); // replace it with whatever you want to do with the row, key=row1/row2/row3
    console.log(colorPicker[0]['rows'][key].divs);
    //for getting all colors
    var temp = colorPicker[0]['rows'][key]["colors"];
    $.each(temp, function(key1){
        console.log(temp[key1]);
    });
});

10-07 17:35