[英]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: “textNodes[1].options.aaah”不是 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.您打算使用id: 1
获取 object 不适用于textNodes[1]
,因为textNodes
是一个只有一个元素的数组。 The object in question is valid at textNodes[0]
because of this.因此,所讨论的 object 在textNodes[0]
处有效。
Then, once you resolve this, the textNodes[0].options.ahhh()
line will still fail because the options
property is also an array.然后,一旦您解决了这个问题, textNodes[0].options.ahhh()
行仍然会失败,因为options
属性也是一个数组。 You want to reference the first (and only) element the same way: textNodes[0].options[0].ahh()
.您希望以相同的方式引用第一个(也是唯一的)元素: textNodes[0].options[0].ahh()
。 This will print ahhh
to the console as intended.这将按预期将ahhh
打印到控制台。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.