我想在 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"
}]
}]
我想访问“Warnings”的“content”属性,而不执行 for 循环。我当前正在执行的访问操作如下:
var content;
for(a in array) {
if(a.title == "Warnings") {
content = a.content;
break;
}
}
这在 javascript 中可行吗?
最佳答案
处理此问题的最佳方法可能是将数据更改为对象,并通过“标题”访问对象元素:
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"
}
]
}
};
然后,您可以通过 data.Warnings
访问警告,并通过 data.Errors
访问错误。
如果您不介意 null 导致测试失败,您可以使用 if (data.Warnings)
或 if (data.Errors)
来测试它们是否存在,或者if (data.Warnings === undefined)
如果您想测试数据是否存在。
使用此更新的格式,要访问与数据不可用时返回的“”类似的警告内容,您可以使用以下内容:
var 内容 = data.Warnings ? data.Warnings.content : '';
关于javascript - 在javascript中访问数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17304931/