如何使用纯JavaScript获取数组movies中对象的theatricalrelease属性
如何获取数组中每个对象的指定属性值
看起来你之前应该是在遍历对象时不小心打印了属性名称,而非对应的值~这是很常见的小失误,我给你几种简单直接的方法来获取每部电影的theatricalrelease属性:
方法一:基础for循环遍历数组
先遍历movies数组里的每一个电影对象,再直接通过.或[]访问目标属性:
// 假设你的movies数组结构示例 const movies = [ { title: "星际穿越", theatricalrelease: "2014-11-07" }, { title: "盗梦空间", theatricalrelease: "2010-09-01" }, { title: "敦刻尔克", theatricalrelease: "2017-07-21" } ]; // 遍历数组获取属性值 for (let i = 0; i < movies.length; i++) { const releaseDate = movies[i].theatricalrelease; console.log(releaseDate); }
方法二:forEach简化遍历
用数组内置的forEach方法,代码更简洁易读:
movies.forEach(movie => { console.log(movie.theatricalrelease); });
方法三:map收集所有属性值到新数组
如果需要把所有theatricalrelease值整理成一个新数组,map方法是最佳选择:
const allReleaseDates = movies.map(movie => movie.theatricalrelease); console.log(allReleaseDates); // 输出所有上映日期组成的数组
为什么你之前拿到的是索引/属性名?
大概率是你在嵌套循环里错误打印了属性名称而非值,比如类似这样的错误写法:
// 错误示例:打印了属性名而非属性值 for (let i = 0; i < movies.length; i++) { for (let prop in movies[i]) { console.log(prop); // 这里输出的是"title"、"theatricalrelease"这类属性名 } }
如果一定要用嵌套循环,改成console.log(movies[i][prop])就能拿到值,但其实没必要这么麻烦——既然你明确知道要找的属性是theatricalrelease,直接访问反而更高效~
内容的提问来源于stack exchange,提问作者cfoster5
相关产品推荐
相关产品推荐

