gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:45:14 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com