javascript 使用方括号 (`[]`) 和点 (`.`) 表示法的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17189642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:25:19  来源:igfitidea点击:

Difference between using bracket (`[]`) and dot (`.`) notation

javascriptsyntax

提问by Maizere Pathak.Nepal

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?

另外为什么.运营商不允许使用 index 属性?

回答by Felix Kling

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

访问成员.称为点符号。访问它们[]称为括号符号

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

点符号仅适用于作为有效标识符名称[spec] 的属性名称,因此基本上任何名称也是有效的变量名称(有效标识符,另请参阅哪些字符对 JavaScript 变量名称有效?)和任何保留关键字[规格].

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.

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

Examples:

例子:

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


Use bracket notation:

使用括号表示法:

  • 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"].
  • 当属性名称包含在变量中时,例如obj[foo].
  • 属性名称包含标识符中不允许的字符,例如以数字开头, 或包含空格或破折号 ( -),例如obj["my property"]

Use dot notation:In all other situations.

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

There is a caveatthough 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.

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



?: 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.

?: 这也是你只能使用方括号来访问数组元素的原因。标识符不能以数字开头,因此不能只由数字组成。

回答by Alberto Zaccagni

You should use .when you know the name of the property

.当您知道属性名称时应该使用

var object = {};
object.property = 'whatever';

, use []when the name of the property is contained in a variable

,[]当属性名称包含在变量中时使用

var object = {};
var property = 'another-property';
object[property] = 'whatever';

As @DCoder added certain object properties cannot be accessed without using the []notation because their names break the syntax. E.g. properties named class, default, or data-prop-value

由于@DCoder 添加了某些对象属性,因此在不使用[]表示法的情况下无法访问它们,因为它们的名称破坏了语法。例如,名为classdefault或 data-prop-value 的属性

回答by Esailija

Also why doesn't . operator allow the index property? I really want full reason. Thank you.

还有为什么没有。运算符允许索引属性?我真的想要充分的理由。谢谢你。

Well if that was possible, consider:

好吧,如果可能的话,请考虑:

var a = 0.5;

Did you mean the number 0.5or access the 5element of the number? See:

您是指数字0.5还是访问数字的5元素?看:

Number.prototype[5] = 3;

0[5] //3
0.5 // 0.5

If you allowed the syntax 0.5to be equal to 0[5], then how do you know what you mean?

如果你允许语法0.5等于0[5],那么你怎么知道你的意思?

It is however possible to use numbers directly with object literal:

然而,可以直接将数字与对象字面量一起使用:

var a = {
    0: 3,
    1: 5
};

回答by Vivek Mehta

Both dot operator and index(bracket notation) operator are used to access the property of an Object. Generally accessing with dot operator is quite faster because accessing variables by window is significantly slower though. But in case of special character in the variables, you cannot use dot operator as it will give error. For such cases we need to use index operator and pass the variable name as a string format means underdouble quote otherwise it will give undefined error. e.g-

点运算符和索引(括号表示法)运算符都用于访问对象的属性。通常使用点运算符访问速度相当快,因为​​通过窗口访问变量要慢得多。但是如果变量中有特殊字符,则不能使用点运算符,因为它会出错。对于这种情况,我们需要使用索引运算符并将变量名作为字符串格式传递,这意味着双引号下,否则会给出未定义的错误。例如-

var abc = {
    font-size : "12px"
} 
Using dot operator - abc.font-size;           //it will give error (Incorrect)
Using index operator - abc["font-size"];      //12px (Correct)