使用方括号 (`[]`) 和点 (`.`) 表示法的区别 [英] Difference between using bracket (`[]`) and dot (`.`) notation

查看:46
本文介绍了使用方括号 (`[]`) 和点 (`.`) 表示法的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 []. 访问数组或对象属性的真正区别是什么?使用哪一种?

What is the real difference in using [] and . for accessing array or object properties? Which one to use?

还有为什么 . 运算符不允许索引属性?

Also why doesn't . operator allow the index property?

推荐答案

使用访问成员.被称为点符号.使用 [] 访问它们称为括号表示法.

Accessing members with . is called dot notation. Accessing them with [] is called bracket notation.

点符号仅适用于有效的属性名称标识符名称 [spec],所以基本上任何名称也是有效的变量名(有效的标识符,另见哪些字符对 JavaScript 变量名有效?) 和任何 保留关键字[spec].

The dot notation only works with property names which are valid identifier names [spec], so basically any name that would also be a valid variable name (a valid identifier, see also What characters are valid for JavaScript variable names?) and any reserved keyword [spec].

括号表示法需要一个计算结果为字符串的表达式(或可以强制为字符串),因此您可以使用任何字符序列作为属性名称.字符串可以包含的内容没有限制.

Bracket notation expects an expression which evaluates to a string (or can be coerced to a string), so you can use any character sequence as property name. There are no limits to what a string can contain.

示例:

obj.foo;  // valid
obj.else  // valid, reserved keywords are valid identifier names
obj.42    // invalid, identifier names cannot start with numbers
obj.3foo  // invalid,                ""
obj.foo-bar // invalid, `-` is not allowed in identifier names

obj[42]   // valid, 42 will be coerced to "42"
obj["--"] // valid, any character sequence is allowed
obj[bar]  // valid, will evaluate the variable `bar` and 
          // use its value as property name

<小时>

使用括号表示法:

  • 当属性名称包含在变量中时,例如obj[foo].
  • 属性名称包含标识符中不允许的字符,例如以数字开头,或包含空格或破折号 (-),例如obj["my property"].
  • When the property name is contained in a variable, e.g. obj[foo].
  • The property name contains characters not permitted in identifiers, e.g. starts with a digit, or contains a space or dash (-), e.g. obj["my property"].

使用点表示法:在所有其他情况下.

有一个关于保留关键字的警告.虽然规范允许将它们用作属性名称并使用点符号,但并非所有浏览器或工具都尊重这一点(尤其是较旧的 IE 版本).因此,我认为最好的解决方案是避免对属性名称使用保留关键字,或者如果不能,请使用括号表示法.

There is a caveat though regarding reserved keywords. While the specification permits to use them as property names and with the dot notation, not all browsers or tools respect this (notably older IE versions). So the best solution in my opinion is to avoid using reserved keywords for property names or use bracket notation if you cannot.

†:这也是您只能使用括号表示法访问数组元素的原因.标识符不能以数字开头,因此不能只由数字组成.

†: That's also the reason why you can only use bracket notation to access array elements. Identifiers cannot start with digits, and hence cannot consist only of digits.

这篇关于使用方括号 (`[]`) 和点 (`.`) 表示法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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