Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

javascript - JavaScript属性访问:点符号与方括号?(JavaScript property access: dot notation vs. brackets?)

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.

(上下文:我已经编写了一个代码生成器来生成这些表达式,我想知道哪种更好。)

  ask by Mark Renouf translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(Sourced from 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 

including non-ASCII (UTF-8) characters, as in myForm["ダ"] ( more examples ).

(包括非ASCII(UTF-8)字符,如myForm["ダ"]更多示例 )。)

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:

(围捕:)

  • 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

    (方括号表示法允许访问包含特殊字符的属性以及使用变量选择属性)


Another example of characters that can't be used with dot notation is property names that themselves contain a dot .

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

For example a json response could contain a property called bar.Baz .

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...