JavaScript 属性访问:点符号与括号? [英] JavaScript property access: dot notation vs. brackets?

查看:26
本文介绍了JavaScript 属性访问:点符号与括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在代码中:

//给定:var foo = {'bar': 'baz'};//然后var x = foo['bar'];//对比var x = foo.bar;

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

解决方案

(来源于 此处.)

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

<块引用>

var foo = myForm.foo[];//错误的语法var foo = myForm["foo[]"];//正确的语法

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

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

<块引用>

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

综述:

<块引用>
  • 点表示法写起来更快,读起来更清晰.
  • 方括号表示法允许访问包含特殊字符和选择使用变量的属性

<小时>

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

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

var foo = myResponse.bar.Baz;//错误的语法var foo = myResponse["bar.Baz"];//正确的语法

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.

解决方案

(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).

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.

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

这篇关于JavaScript 属性访问:点符号与括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆