JavaScript 属性访问 : dot notation vs. 括号?

标签 javascript syntax object-literal

除了第一种形式可以使用变量而不仅仅是字符串文字这一明显事实之外,是否有任何理由使用其中一个而不是另一个,如果是,在什么情况下?

在代码中:

// Given:
var foo = {'bar': 'baz'};

// Then
var x = foo['bar'];

// vs. 
var x = foo.bar;

上下文:我编写了一个代码生成器来生成这些表达式,我想知道哪个更可取。

最佳答案

(源自here。)

方括号表示法允许使用不能与点表示法一起使用的字符:

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

包括非 ASCII (UTF-8) 字符,如 myForm["ダ"] ( more examples )。

其次,方括号表示法在处理 以可预测的方式变化的属性名称:

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

综述:

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables
<小时/>

不能与点表示法一起使用的字符的另一个示例是本身包含点的属性名称。

例如,json 响应可能包含名为 bar.Baz 的属性。

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

关于JavaScript 属性访问 : dot notation vs. 括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57978724/

相关文章:

javascript - new vs object create给出不同的结果OO javascript

javascript - 有没有 ? ("safe operator") Typescript 中的替代方法来处理空值?

javascript - 如果不是AJAX调用的某个文件则重写

javascript - 递增 1,然后 10,然后 100?

Javascript/jQuery .each 和语法问题

javascript - javascript 引擎解释对象字面量时发生了什么?

jquery - 回发后元素在 jQuery 对象中保留原始值

javascript - Bootstrap 调整页面大小未找到视口(viewport)

c - 不确定这行代码在c中的作用

c - 为什么这段代码没有重声明错误呢?