简体   繁体   中英

Pulling array from object

Im trying to pull the gpa numbers from the array that is in the object and have them displayed in the console but my code keeps giving me undefined '0' error. Any help would be appreciated.

var fsInfo = {
    name: 'John Doe',
    address:{
        street: '123 Some Street ',
        city: 'Town, ',
        state: 'HI',
    gpa: [3.0,4.0,2.0]
    }
 }

console.log("GPA: " + fsInfo.gpa['0'],fsInfo.gpa['1'],fsInfo.gpa['2'])

Use

console.log("GPA: " + fsInfo.gpa[0],fsInfo.gpa[1],fsInfo.gpa[2])

Note: Array indices are numbers.

In your case, they are inside address . So you should do

console.log("GPA: " + fsInfo.address.gpa[0],fsInfo.address.gpa[1],fsInfo.address.gpa[2])

If your object had been like this

var fsInfo = {
    name: 'John Doe',
    address:{
        street: '123 Some Street ',
        city: 'Town, ',
        state: 'HI'
    },
    gpa: [3.0,4.0,2.0]
 }

then

console.log("GPA: " + fsInfo.gpa[0],fsInfo.gpa[1],fsInfo.gpa[2])

will work.

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