使用普通的Javascript,我正在尝试访问数组theatricalrelease
中所有对象的属性movies
。
var movies = [{
"Black Panther" : {
"title" : "Black Panther",
"theatricalrelease" : "2/16/2018"
},
"Infinity War" : {
"title" : "Avengers: Infinity War",
"theatricalrelease" : "5/4/2018"
},
"Captain Marvel" : {
"title" : "Captain Marvel",
"theatricalrelease" : "TBA"
}
}];
for (var i = 0; i < movies.length; i++) {
console.log(movies[i]);
//TRIED
for (var property in movies[i]) {
if (movies[i].hasOwnProperty(property)) {
console.log(property);
}
}
}
}
&#13;
正如你所看到的,我试图在另一个循环中使用另一个for循环,因为我希望它循环遍历对象的索引名称。相反,记录property
给了我每个索引的名称。
如何访问每部电影的戏剧版?
答案 0 :(得分:2)
问题是您在代码底部有一个对象和一个额外}
括号的数组。我对你的阵列进行了一些修改,以达到我的目的。现在,您可以在console.log
打印剧场版。
var movies = [{
"title" : "Black Panther",
"theatricalrelease" : "2/16/2018"
},{
"title" : "Avengers: Infinity War",
"theatricalrelease" : "5/4/2018"
},{
"title" : "Captain Marvel",
"theatricalrelease" : "TBA"
}];
for (var i = 0; i < movies.length; i++) {
console.log(movies[i]);
console.log('theatrical release', movies[i]['theatricalrelease'])
}
&#13;
答案 1 :(得分:1)
根据您的方法: 只有一个元素:
var movies = [{ "title": "Black Panther", "theatricalrelease": "2/16/2018"}, { "title": "Avengers: Infinity War", "theatricalrelease": "5/4/2018"}, { "title": "Captain Marvel", "theatricalrelease": "TBA"}];
movies.forEach(({theatricalrelease}) => console.log(theatricalrelease));
.as-console-wrapper { max-height: 100% !important; top: 0; }