关于 [] 和 .(点dot) 的杂谈

作为一个懒人,在JS .[]之间总是选择.,今天查资料时,倒是看到了 “点” 和 “括号”的一些区别。这里抛砖引玉一下

先看一个常见例子:

1
2
3
4
5
var obj = { "say" : "hello" };
var x = "say";
var y = obj[x];
console.log(y); // hello
obj.x // undefine

在上面这种情况下,使用点obj.x 是没有效果的

查阅官网,有这么一句话— The dot notation only works with property names which are valid identifier names
即点(dot)只能被用来访问 有效的标识符名称,而括号[]会按照字符串(string)进行处理,甚至可以强制作为字符串。这样在括号中就可以使用任何字符序列作为属性名称。(因为字符串包含的内容是不受限制的)。

eg:

1
2
3
4
5
6
7
8
9
10
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

综上:

  1. 当属性名称包含在变量中取值(第一种情况) 用大括号
  2. 当属性名称中含有 非有效 的标识符,包括但不限于 数字,空格,-等等,请务必用[],而不能使用.(dot)