我试图定位数组中每个对象中的特定项目,以便将它们用作其他地方的变量。如何使用每个项目创建变量?类似于 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/