gpt4 book ai didi

javascript - 向 Javascript 对象添加属性

转载 作者:行者123 更新时间:2023-12-03 00:37:17 25 4
gpt4 key购买 nike

myTable.div 将返回“div_undefined”。当我改变时div: 'div_' + this.namediv: 'div_' + myTable.name它会抛出一个错误:

Uncaught TypeError: Cannot read property 'name' of undefined at :3:26

。有什么想法吗?

var myTable = {
name: 'tablename',
div: 'div_' + this.name
}
console.log(myTable.div);

最佳答案

您可以首先声明您的对象,然后添加div属性:

myTable.div = 'div_' + myTable.name;

请记住,如果您选中 MDN Object reference,则对象始终可以使用更多属性进行扩展。 你可以看到:

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed.

演示:

var myTable = {
name: 'tablename'
};
myTable.div = 'div_' + myTable.name;
console.log(myTable);

关于javascript - 向 Javascript 对象添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53610777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com