gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:02:53 26 4
gpt4 key购买 nike

除了第一种形式可以使用变量而不仅仅是字符串文字这一显而易见的事实之外,还有什么理由使用一个而不是另一个,如果是,在哪些情况下?

在代码中:

// 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/4968406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com