javascript - 如何定位数组中对象的内容?

标签 javascript jquery

我试图定位数组中每个对象中的特定项目,以便将它们用作其他地方的变量。如何使用每个项目创建变量?类似于 var thisThing = things.title; ?

things: [
    {title: "The title for this thing", url: "https://stackoverflow.com"},
    {title: "The title for this thing", url: "https://stackoverflow.com"},
    {title: "The title for this thing", url: "https://stackoverflow.com"},
    {title: "The title for this thing", url: "https://stackoverflow.com"}
    ]

最佳答案

实现这一目标的一种方法是使用 ES6 object destructuring 。只需将变量名称括在大括号中,以便它们与对象属性的名称匹配。例如:

const things = [{
    title: "The title for this thing 1",
    url: "https://stackoverflow.com"
  },
  {
    title: "The title for this thing 2",
    url: "https://stackoverflow.com"
  },
  {
    title: "The title for this thing 3 ",
    url: "https://stackoverflow.com"
  },
  {
    title: "The title for this thing 4",
    url: "https://stackoverflow.com"
  }
];


things.forEach(thing => {
  const {title, url} = thing;
  console.log(title);
  console.log(url);
  console.log('');
})

如果您正在按照 ES6 之前的规范进行编码,则可以简单地使用索引来访问数组中的元素并使用点表示法来获取属性值(正如 TJ 在他的评论中提到的那样):

console.log(things[0].title)

关于javascript - 如何定位数组中对象的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57576774/

相关文章:

javascript - 单个属性上的多个 jQuery 选择器条件?

javascript - .ondragstart 不等同于 .addEventListener ("dragstart"

javascript - 禁用 Chrome 严格的 MIME 类型检查

jquery - geocomplete_rails 和 Uncaught ReferenceError : google is not defined

Jquery 检查整数?

php - 如何在 Jquery 表格中显示图像?

Javascript API - 可选 js sdk 模块未定义

JavaScript 继承未按预期工作

javascript - 从 React Native 和 expo 调用本地域

jQuery:带有隐藏输入字段的动画