Javascript 对象文字不允许引用现有值?

标签 javascript

我有一个对象,定义如下:

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:

  1. 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/

相关文章:

Javascript:匹配使用 dom 加载页面

javascript - Javascript 正则表达式中的特定阿拉伯单词

java - java变量的奇怪行为

javascript - 意外使用 'screen' no-restricted-globals reactjs

javascript - 无法从图库/库中选择视频 -phonegap/cordova

javascript - jQuery:如何查找具有特定 id 的 li 标签

javascript - 纸js绘图(项目/路径)层次结构

javascript - 在 for-of 循​​环中等待与在 for-of 之前获取可迭代对象

javascript - 如何防止输入 Ctrl S 时弹出 OS "Save As"对话框

javascript - 如何计算嵌套数组中的项目数?