在对象的键值对中指定键时使用字符串

Using strings when specifying a key in an object's key-value pair

在对象的键值对中指定键时(使用下面的表示法),解释器(显然)允许使用字符串:

var x = { 'color': '#fff' };

但是,不允许使用函数(returns 字符串)动态指定键:

function s()
{
    return 'color';
}

var x = { s(): '#fff' };

我猜字符串在使用该表示法时必须是静态值。

但是我找不到 JavaScript 语言规范...

在这种情况下你应该使用这个方法:

var x = {};
x[s()] = "#fff";
x[foo()] = "#000";

"Associative arrays" 在 Javascript 中不存在。您可能指的是对象。这是学习JS时很常见的错误。

一个 Object 可以使用 { } 初始化,或者像这样用 new 运算符初始化:

var x = {};
var y = {foo : 'bar'};
var z = new Object();

访问对象属性时,您可以使用 .运算符或括号。

var somevalue = y.foo;   // 'bar'
var someother = y['foo'] // 'bar'

在你目前的情况下,你会想要这样的东西:

var x = new Object();  // or {}
x[s()] = "#fff";

对象类型

如果检查 x 的 type,它将 return 'object'.

var typeOfX = typeof x;  // 'object' 

根据this MDN article(我用粗体突出显示):

The syntax for an object using an object initializer is:

var obj = { property_1:   value_1,   // property_# may be an identifier...
            2:            value_2,   // or a number...
            // ...,
            "property n": value_n }; // or a string

where obj is the name of the new object, each property_i is an identifier (either a name, a number, or a string literal), and each value_i is an expression whose value is assigned to the property_i.

因此,在这种文字表示法中,不允许对表达式求值,例如通过函数调用来确定 属性 标识符。

ECMAScript Language Specification中更正式地说:

PropertyName:

  • IdentifierName
  • StringLiteral
  • NumericLiteral

ECMAScript 2015

使用 ECMAScript 2015 可以实现更多功能,如 this MDN article 中所述:

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [ ], that will be computed as the property name.

// Computed property names (ES6)
var i = 0;
var a = {
  ["foo" + ++i]: i,
  ["foo" + ++i]: i,
  ["foo" + ++i]: i
};

ECMAScript 2015 Language Specification中的正式定义有:

PropertyName:

  • LiteralPropertyName
  • ComputedPropertyName

ComputedPropertyName:

  • [ AssignmentExpression ]

因此,使用 ES6,您可以像这样重写您的示例:

function s()
{
    return 'color';
}

var x = { [s()]: '#fff' };