使用连接(动态)字符串作为JavaScript对象键?

thi*_*one 44 javascript syntax object-literal

var test = "test123"
var test123 ={
    "key" + test: 123
}
Run Code Online (Sandbox Code Playgroud)

此代码不起作用."关键"+测试有什么问题?

pim*_*vdb 66

因为它"key" + test是一个表达式而不是标识符,也不是字符串文字,也不是数字文字,它们是唯一被允许作为对象文字中的键的东西.

[]在为这样的动态密钥创建对象后,必须使用该表示法:

var test123 = {};
test123["key" + test] = 123;
Run Code Online (Sandbox Code Playgroud)

标识符基本上是您可以调用变量的字符的子集(字母,数字_和$;可能不以数字开头),字符串文字是用'或括起来的任何字符串".

因此,您可以在对象文字中使用的唯一键类型是:

{
  a0:   true, // valid identifier
  $$_:  true, // same
  123:  true, // valid numeric literal
  012:  true, // same (octal)
  0xf:  true, // same (hex)
  "@":  true, // not allowed as an identifier
  '0a': true  // same
}
Run Code Online (Sandbox Code Playgroud)

参考:http://es5.github.com/#x11.1.5.

PropertyName:

IdentifierName

字符串字面量

NumericLiteral

  • 此外,对象文字中也允许使用数字,例如"0"或"5e10"(但不是"-10",因为`-`不是数字文字的一部分,而是一元的`-`运算符). (3认同)

Ben*_*Ben 49

使用ES6,您可以在对象文字中定义动态键:

const test = "test123"
const test123 = { [`key${test}`]: 123 };  //{ keytest123: 123 }
Run Code Online (Sandbox Code Playgroud)


max*_*max 10

您可以但不能使用文字符号(ES6之前).

var test123 = {};
test123["foo" + "bar"] = 'baz';

test123.foobar === 'baz'; // true
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的简单回答,这正是我一直在寻找的:) (2认同)