除了第一种形式可以使用变量而不仅仅是字符串文字这一显而易见的事实之外,是否有理由使用其中一种而不是另一种,如果是这样,在哪些情况下使用呢?
代码:
// Given:
var foo = {'bar': 'baz'};
// Then
var x = foo['bar'];
// vs.
var x = foo.bar;
上下文:我已经编写了一个生成这些表达式的代码生成器,我想知道哪个更可取.
除了第一种形式可以使用变量而不仅仅是字符串文字这一显而易见的事实之外,是否有理由使用其中一种而不是另一种,如果是这样,在哪些情况下使用呢?
代码:
// Given:
var foo = {'bar': 'baz'};
// Then
var x = foo['bar'];
// vs.
var x = foo.bar;
上下文:我已经编写了一个生成这些表达式的代码生成器,我想知道哪个更可取.
(来源于here.)
Square bracket notation allows the use of characters that can't be used with dot notation:
var foo = myForm.foo[]; // incorrect syntax var foo = myForm["foo[]"]; // correct syntax
包括非ASCII(UTF-8)字符,如myForm["ダ"]
(more examples).
Secondly, square bracket notation is useful when dealing with property names which vary in a predictable way:个
for (var i = 0; i < 10; i++) { someFunction(myForm["myControlNumber" + i]); }
Roundup:个
- 点符号书写速度更快,阅读更清晰.
- 方括号表示法允许访问包含
另一个不能与点符号一起使用的字符示例是property names that themselves contain a dot.
例如,json响应可以包含一个名为bar.Baz
的属性.
var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax