简体   繁体   中英

Calling a method from a nested object in an array (javascript)

EDIT: Took out the unnecessary bit

Not sure why i can't call this method - I get an error

"textNodes[1].options.aaah" is not a function:

 const textNodes = [{ id: 1, room_id: 1, text: '"ZZZZzzzzZZZZZZzzzzzzzzzzZZZZZZZZZZZZZ"', options: [{ text: "Wake up", setfadeMode: { fade: 2 }, nextText: 2, ahhh() { console.log("ahhh"); }, }, ], }, ]; textNodes[1].options.ahhh();

Your intention of getting the object with id: 1 will not work with textNodes[1] since textNodes is an array with just one element. The object in question is valid at textNodes[0] because of this.

Then, once you resolve this, the textNodes[0].options.ahhh() line will still fail because the options property is also an array. You want to reference the first (and only) element the same way: textNodes[0].options[0].ahh() . This will print ahhh to the console as intended.

See the result below for verification of this solution.

 const textNodes = [{ id: 1, room_id: 1, text: '"ZZZZzzzzZZZZZZzzzzzzzzzzZZZZZZZZZZZZZ"', options: [{ text: "Wake up", setfadeMode: { fade: 2 }, nextText: 2, ahhh() { console.log("ahhh"); }, }, ], }, ]; textNodes[0].options[0].ahhh();

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