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

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

问题描述

除了显而易见的事实,即第一种形式可以使用变量而不仅仅是字符串文字,是否有任何理由使用其中一种,如果是这样的话?

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?

代码:

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

推荐答案

(来自这里。)

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


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


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


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


综述:



  • 点符号编写速度更快,阅读更清晰。

  • 方括号表示法允许访问包含
    特殊字符的属性,并使用变量选择
    属性






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

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

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天全站免登陆