简体   繁体   English

JavaScript 从数组内的对象中获取一个属性

[英]JavaScript get one property from an object inside of an array

I have an array of movies objects with the properties: movieName, grade, and position.我有一组具有以下属性的电影对象:movieName、grade 和 position。 For example these objects look like:例如,这些对象看起来像:

var movies = [ { movieName: "bee movie", grade: 3, position 1},
               { movieName: "Shrek", grade: 5, position: 2} ];

I want to get the movieName property of an object.我想获取一个对象的 movieName 属性。 To decide which object from the movies array I want the movieName from I create a variable named arrayPosition which is a random number between 0 and the length of the array - 1:为了决定我想要电影数组中的哪个对象,我创建了一个名为 arrayPosition 的变量,它是一个介于 0 和数组长度 - 1 之间的随机数:

arrayPosition = Math.floor(Math.random() * movies.length );

For example:例如:

 var movies = [{ movieName: "Incredibles", grade: 4, position: 1 }, { movieName: "Bolt", grade: 5, position: 2 } ]; const arrayPosition = Math.floor(Math.random() * movies.length); console.log(movies[arrayPosition].movieName);

In this case I would like it to console either "Incredibles" or "Bolt" depending on if arrayPosition is 0 or 1 but it only consoles undefined.在这种情况下,我希望它根据 arrayPosition 是 0 还是 1 来控制“Incredibles”或“Bolt”,但它只控制未定义的控制台。

I have seen solutions to similar problems but in those cases the position of the object in the array was not a variable but a decided number.我见过类似问题的解决方案,但在这些情况下,对象在数组中的位置不是变量而是确定的数字。 For some reason this difference make it not work.由于某种原因,这种差异使它不起作用。 How do I get only the movieName property from an object in the array?如何仅从数组中的对象获取 movieName 属性?

Your example code works correctly.您的示例代码工作正常。

 var movies = [ { movieName: "bee movie", grade: 3, position: 1}, { movieName: "Shrek", grade: 5, position: 2}, { movieName: "Incredibles", grade: 4, position: 1}, { movieName: "Bolt", grade: 5, position: 2} ]; var arrayPosition = Math.floor(Math.random() * movies.length) console.log(movies[arrayPosition].movieName)

If you knew that you always wanted to console.log the title of the 2nd movie in the array, you could instead do:如果你知道你总是想在console.log数组中记录第二部电影的标题,你可以这样做:

 var movies = [ { movieName: "bee movie", grade: 3, position: 1}, { movieName: "Shrek", grade: 5, position: 2}, { movieName: "Incredibles", grade: 4, position: 1}, { movieName: "Bolt", grade: 5, position: 2} ]; var arrayPosition = 1 console.log(movies[arrayPosition].movieName)

Remember that:请记住:

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1. JavaScript 数组是零索引的:数组的第一个元素位于索引 0 处,最后一个元素位于等于数组长度属性值减 1 的索引处。

Using an invalid index number returns undefined.使用无效的索引号会返回 undefined。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM