[英]How to add an object constructor into an empty array that is within another object
[英]How to add an empty array to object?
我无法通过方括号表示法将空数组添加到对象中。 我知道如何通过点表示法将空数组放入对象中,但是我只是不明白为什么括号表示法对我不起作用。
更新 :我现在了解我的问题; 点表示法和方括号表示法之间的上下文切换使我蒙蔽了我,我完全没想起在我的第三个区块中-animal [noises](忘记了“”)试图访问属性噪音的属性值,而我没有在我的对象中创建
创建并向我的对象添加属性
var animal = {};
animal.username = "Peggy";
animal["tagline"] = "Hello";
然后将创建以下内容:
animal {
tagline: "Hello",
username: "Peggy"
}
当我尝试将以下内容添加到对象中时为什么不起作用?
var noises = [];
animal[noises];
我在控制台中得到了(与上面相同):
animal {
tagline: "Hello",
username: "Peggy"
}
我能够通过这种方式获得结果:
animal.noises = [];
哪个输出到我的控制台:
animal {
noises: [],
tagline: "Hello",
username: "Peggy"
}
但这仍然使我想到一个问题:为什么不能通过括号表示法起作用?
采用
animal.noises = noises;
要么
animal['noises'] = noises;
就像您在使用animal[noises];
这意味着当您尝试从对象读取数据时。
对于animal[noises]
,
animal
是对象 noises
是animal
的关键/属性 而且数组不能是键。 如果要将noises
数组放入animal
对象中,可以按以下步骤进行操作,
animal['noises'] = noises;
在您的情况下,您必须尝试
animal['noises']=noises
Array []
表示法用于获取需要用引号引起来的对象的属性。 数组符号通常用于获取包含特殊字符的对象的标识符。
var animal={
"@tiger":'carnivore' // you can't have @tiger without quote as identifier
}
console.log(animal.@tiger) // it will give ERROR
console.log(animal['@tiger']) // it will print out 'carnivore'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.