关于访问对象和添加属性,我需要一些说明,我是 Javascript 的新手。
我有一个像这样的对象:
var device = {
dev1 : { "version" : "1.0", "name" : "AIR" },
dev2 : { "version" : "1.0", "name" : "BEE" }
}
当我执行这两行时它会出错是有原因的吗? (我没有使用浏览器,而是作为应用程序纯粹在 Javascript 上运行。)
console.log( device.dev1['version'] ) returns undefined
console.log( device['dev1'].version ) returns undefined
现在添加属性...我想使用 String 类型的属性键名。意思是我不希望它看起来像这样。它必须遵循我上面使用“”描述的对象。
dev1 : { version : "1.0", name: "AIR" }
有没有办法将属性名称定义为字符串?可以这样做吗?
var newKey = "health";
device['dev1'].newKey = newValue;
非常感谢!
最佳答案
一旦我修复了你的语法错误,你的代码就可以正常工作了:
var device = {
dev1 : { "version" : "1.0", "name" : "AIR" }, // added comma here
dev2 : { "version" : "1.0", "name" : "BEE" }
};
console.log( device.dev1['version'] ); // 1.0
console.log( device['dev1'].version ); // 1.0
console.log( device.dev1.version ); // 1.0
属性名称总是 字符串。它们不可能是其他任何东西。如果看起来属性名称不是字符串,则它只是字符串的简写。
当属性名称是变量中的字符串时,您可以使用括号语法来获取和设置:
var newKey = 'someName';
var newValue = 'woot';
device.dev1[newKey] = newValue;
console.log(device.dev1[newKey]); // woot
console.log(device.dev1.someName); // woot
因此,如果您提前知道属性名称,则简写点属性语法 obj.propName
与 obj['propName']
相同。但是如果你事先不知道属性名,那么你必须使用方括号语法。 obj[propNameString]
关于Javascript 对象和属性 : Adding & Accessing Properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242087/