javascript - 在javascript中访问数组的元素

标签 javascript

我想在 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/

相关文章:

javascript - 在添加复选框事件的 react 中未定义“this”

javascript - 如何在使用 jQuery 单击按钮后跳转到特定幻灯片?

javascript - 如何设置存储在 JS 变量中的 div 类的样式?

javascript - 选择选项更改时调用函数

javascript - "The stylesheet was not loaded because its MIME type, "文本/html "is not "文本/css"

javascript - 将 Canvas 放大到父级的宽度和高度

javascript - captureStream() 中的第一帧未发送

javascript - 动态着色文本

javascript - 如何清除 angularJS 数组

php - JS OnClick 事件将执行 php 代码块