使用连接的(动态)字符串作为 JavaScript 对象键? [英] Use a concatenated (dynamic) string as JavaScript object key?
问题描述
var test = "test123"
var test123 ={
"key" + test: 123
}
此代码不起作用."key" + test 有什么问题?
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;
标识符基本上是可以调用变量的相同字符子集(字母、数字、_
和 $
;不能以数字开头),并且字符串文字是用 '
或 "
括起来的任何字符串.
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.
属性名称:
标识符名称
字符串文字
数字文字
这篇关于使用连接的(动态)字符串作为 JavaScript 对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!