我有一个对象,定义如下:
var obj = {
'title': 'foo',
'id': '123',
'category': 'aaa',
'meta': 'blah blah'
};
我想对其进行子集化,但是,我在 JS 中发现了一些我不理解的行为:
var foo = {obj.title: obj.id}; // doesn't work
var bar = {obj['title']: obj['id']}; // this doesn't either
var baz = {}
baz[obj.title] = obj.id // this works fine.
为什么?
最佳答案
因为这是在 ECMAScript 5, Section 11.1.5 中定义的方式:
属性名称必须是:
PropertyName : IdentifierName StringLiteral NumericLiteral
obj.title
既不是 identifier name ,也不是字符串或数字文字。但即使您之前将标题分配给另一个变量,您也会看到生产规则不会评估标识符:
The production PropertyName : IdentifierName is evaluated as follows:
- Return the String value containing the same sequence of characters as the IdentifierName.
只是详细说明为什么它不是有效的标识符名称:full stop (.
) 属于 Puncuation, other [Po]类别,这不是允许字符的一部分。其中包括:
UnicodeLetter: any character in the Unicode categories "Uppercase letter (Lu)", "Lowercase letter (Ll)", "Titlecase letter (Lt)", "Modifier letter (Lm)", "Other letter (Lo)", or "Letter number (Nl)".
UnicodeCombiningMark: any character in the Unicode categories "Non-spacing mark (Mn)" or "Combining spacing mark (Mc)"
UnicodeDigit: any character in the Unicode category "Decimal number (Nd)"
UnicodeConnectorPunctuation: any character in the Unicode category "Connector punctuation (Pc)"
关于Javascript 对象文字不允许引用现有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8050232/