使用连接(动态)字符串作为JavaScript对象键? [英] Use a concatenated (dynamic) string as JavaScript object key?
问题描述
var test = "test123"
var test123 ={
"key" + test: 123
}
此代码不起作用。 关键+测试有什么问题?
This code doesn't work. What is wrong with "key" + test ?
推荐答案
因为key+ test
是一个表达而不是标识符,字符串文字或数字文字,这是唯一被允许作为对象文字中的键的东西。
Because "key" + test
is an expression and not an identifier nor a string literal nor a number literal, which are the only things that are allowed as the key in an object literal.
你必须使用 []
为这样的动态密钥创建对象后的表示法:
You have to use the []
notation after creating the object for such a dynamic key:
var test123 = {};
test123["key" + test] = 123;
标识符基本上是可以称为变量的字符子集(字母,数字, _
和 $
;可能不以数字开头),字符串文字是用<$ c $括起来的任何字符串c>'或。
An identifier is basically the same subset of characters that you can call a variable (letters, numbers, _
and $
; may not start with a number), and a string literal is any string enclosed with '
or "
.
所以,你可以使用的唯一键类型在对象文字中使用是:
So, the only types of keys you can use in an object literal are:
{
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
}
参考: http://es5.github.com/# x11.1.5 。
PropertyName :
IdentifierName
StringLiteral
NumericLiteral
这篇关于使用连接(动态)字符串作为JavaScript对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!