简体   繁体   中英

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. 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. 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 = 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.

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?

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:

 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.

Using an invalid index number returns undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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