【发布时间】:2022-12-02 13:13:04
【问题描述】:
Other than the obvious fact that the first form could use a variable and not just a string literal, is there any reason to use one over the other, and if so under which cases?
In code:
// Given:
var foo = {\'bar\': \'baz\'};
// Then
var x = foo[\'bar\'];
// vs.
var x = foo.bar;
Context: I\'ve written a code generator which produces these expressions and I\'m wondering which is preferable.
-
Just to chip in, not an answer to your original question (since you\'ve had plenty of good explanations so far), but speed-wise there\'s no difference worth mentioning either: jsperf.com/dot-vs-square-brackets. The above test gives only a 2% margin at best to either of them, they\'re neck and neck.
-
See also How do I add a property to an object using a variable as the name? and Dynamically access object property using variable
-
This question/answer can be used also for UTF-8 keys.
标签: javascript syntax object-literal