这个 Javascript 对象字面量键限制是否严格归因于解析?
请参考下面的代码,当我“注释”任一注释掉的行时,它会导致“':'预期”的错误(在IE中)。那么我的结论是否正确,即无法提供对对象值的引用,作为字符串文字中的对象键;这严格来说是一个解释器/解析问题吗?与 Crockford 的“好部分”相比,这是 Javascript 的一个糟糕(或至少是“坏”)“部分”的候选者吗?
<script>
var keys = {'ONE': 'one'};
//causes error:
//var obj1 = {keys.ONE: 'value1'};
//var obj1 = {keys['ONE']: 'value1'};
//works
var obj1 = {};
obj1[keys.ONE] = 'value1';
//also works
var key_one = keys.ONE;
var obj2 = {key_one: 'value1'};
</script>
Please refer to the code below, when I "comment in" either of the commented out lines, it causes the error (in IE) of "':' expected". So then is my conclusion correct, that this inability to provide a reference to an object value, as an object key in a string literal; is this strictly an interpreter/parsing issue? Is this a candidate for an awful (or at least "bad") "part" of Javascript, in contrast to Crockford's "good parts"?
<script>
var keys = {'ONE': 'one'};
//causes error:
//var obj1 = {keys.ONE: 'value1'};
//var obj1 = {keys['ONE']: 'value1'};
//works
var obj1 = {};
obj1[keys.ONE] = 'value1';
//also works
var key_one = keys.ONE;
var obj2 = {key_one: 'value1'};
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
文字对象语法的限制是名称必须是文字。由于名称可以指定为标识符和字符串,因此不可能使用变量来代替。
这将创建一个具有属性
n
的对象,而不是属性answer
:The limitation of the literal object syntax is that the names has to be literal. As the names can be specified as an identifer as well as a string, it's not possible to use a variable instead.
This will create an object with a property
n
, not a propertyanswer
:使用
{}
定义对象时不能使用变量作为键,因此它们将被解释为字符串名称,并且只能包含可用于变量名称的字符
objectname[anythingThatReturnsValue]='value1'; 是要走的路。
另外,
您还可以生成字符串并解析它。
上述两种方法对于在 JavaScript 中创建对象来说都是不好的做法,我不推荐它们。
You cannot use variables as keys when defining object with
{}
Therefore they are being interpreted as string names and can consist only of characters avaliable for variable names
the
objectname[anythingThatReturnsValue]='value1';
is the way to go.ALSO
You can generate a string and parse it
Both above methods are bad practices for creating objects in JavaScript and I don't recommend them.
想想看:如果它按照你想要的方式工作,它会完全引入语言歧义。
这两个语句在 JavaScript 中是等效的,因为裸字键是“自动引用的”。因此,如果
something
表示文字字符串“something”,那么它如何也可以引用变量“something”。不可以。因此,如果您想使用变量,则必须使用方括号表示法而不是key : value
表示法。Think about it: if it were to work the way you want it would totally introduce a language ambiguity.
The two statements are equivalent in JavaScript, because bareword keys are "autoquoted." So if
something
means the literal string "something", how it could also refer to the variable "something". It can't. So if you want to use variables they have to go in square bracket notation instead ofkey : value
notation.您可以尝试:
You can try: