带有特殊字符或保留字的属性

虽然对象属性表示法通常写为 myObject.property,但这只允许通常在 JavaScript 变量名中找到的字符,主要是字母,数字和下划线(_)。

如果你需要特殊字符,例如空格,☺或用户提供的内容,则可以使用 [] 括号表示法。

myObject['special property ☺'] = 'it works!'
console.log(myObject['special property ☺'])

全数字属性:

除特殊字符外,全数字的属性名称还需要括号表示法。但是,在这种情况下,不需要将属性写为字符串。

myObject[123] = 'hi!' // number 123 is automatically converted to a string
console.log(myObject['123']) // notice how using string 123 produced the same result
console.log(myObject['12' + '3']) // string concatenation
console.log(myObject[120 + 3]) // arithmetic, still resulting in 123 and producing the same result
console.log(myObject[123.0]) // this works too because 123.0 evaluates to 123
console.log(myObject['123.0']) // this does NOT work, because '123' != '123.0'

但是,不建议使用前导零,因为它被解释为八进制表示法。 (TODO,我们应该生成并链接到描述八进制,十六进制和指数表示法的示例)

另请参见:[Arrays are Objects]示例。