0

我想在 javascript 中访问数组中的元素,而无需执行 for 循环来访问它。

这是我的数组:

var array = [{
    "title": "Warnings",
    "numbers": 30,
    "content": [{
        "number": 3001,
        "description": "There may be a problem with the device you are using if you use the default profile"
    }]
}, {
    "title": "Errors",
    "numbers": 20,
    "content": [{
         "number": 1000,
         "description": "No network is loaded"
    }]
}]

我想在不执行 for 循环的情况下访问“警告”的“内容”属性。我目前正在做的访问它如下:

var content;
for(a in array) {
    if(a.title == "Warnings") {
        content = a.content;
        break;
    }
}

这在 javascript 中可行吗?

4

4 回答 4

3

处理此问题的最佳方法可能是将数据更改为对象,并通过“标题”访问对象元素:

var data = {
  "Warnings": {
    "numbers": 30,
    "content": [
      {
        "number" : 3001,
        "description" : "There may be a problem with the device you are using if you use the default profile"
      }
    ]
  },
  "Errors": {
    "numbers": 20,
    "content": [
      {
        "number": 1000,
        "description": "No network is loaded"
      }
    ]
  }
};

然后,您可以访问警告 asdata.Warnings和错误 as data.Errors

您可以测试它们是否存在,if (data.Warnings)或者if (data.Errors)您是否不介意 null 未通过测试,或者if (data.Warnings === undefined)您更愿意测试数据是否存在。

使用这种更新的格式,要访问类似于如果数据不可用时返回的 '' 的警告内容,您可以使用以下内容:

var content = data.Warnings ? data.Warnings.content : '';

于 2013-06-25T18:38:29.037 回答
1
var content = ar.filter(function(v) {
    return v.title == 'Warnings';
})[0].content;
于 2013-06-25T18:45:18.737 回答
0

如果您知道索引,则可以像这样简单地访问它:

array[0].content
于 2013-06-25T18:35:16.450 回答
0

尝试使用http://jsonselect.org/

你可以使用选择器做你想做的事:

.title:val("Warnings") ~ .content
于 2013-06-25T19:05:45.087 回答