0

我有一个 Json 数组,其中包含以下元素:“adjacencies”、“data”、“id”、“name”。在某些元素中,“邻接”是不存在的。这是一个例子:

var JsonArray = [
                 {
                   "id" : "id1",
                   "name" : "name1",
                   "data" : {
                             "$type" : "circle",
                             "$color" : "#AEC43B"
                            }
                 }, //Without "adjacencies"

                 {
                   "id" : "id2",
                   "name" : "name2",
                   "data" : {
                             "$type" : "circle",
                             "$color" : "#AEC43B"
                            }
                 }, //Without "adjacencies"

                 {
                    "adjacencies": [
                                    {
                                     "nodeTo": "id1",
                                     "nodeFrom": "id3",
                                     "data": {
                                              "$color": "#416D9C"
                                             }
                                    }
                                    ],
                    "id" : "id3",
                    "name" : "name3",
                    "data" : {
                             "$type" : "circle",
                             "$color" : "#AEC43B"
                            }
                 } //With "adjacencies"
                ];

第一个和第二个元素不包含“邻接”,但第三个元素包含。在循环中for (i = 0; i < JsonArray.length; i++)如何访问第三个元素?.contain例如,有没有财产?提前致谢:)

4

2 回答 2

2

一种方法是检查值是否为 type undefined

for (i = 0; i < JsonArray.length; i++) {
    var item = JsonArray[i];
    if (typeof item.adjacencies !== "undefined") {
        // item has adjacencies property
    }
}

顺便说一句:这不是 JSON 数组——它是 Javascript 数组。没有 JSON 对象,没有 JSON 数组,没有 JSON。唯一存在的 JSON-y 是纯 JSON,它是一种序列化格式。

于 2012-09-24T08:13:53.607 回答
0

使用 hasOwnProperty

所以你可以这样做

for (i = 0; i < JsonArray.length; i++){
    if( JsonArray[i].hasOwnProperty('adjacencies') ){
        //Do something here
    }
}
于 2012-09-24T08:22:04.417 回答