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

在代码:

// Given:
var foo = {'bar': 'baz'};

// Then
var x = foo['bar'];

// vs. 
var x = foo.bar;

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


当前回答

The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.

So if you know that the property you are interested in is called “length”, you say value.length. If you want to extract the property named by the value held in the variable i, you say value[i]. And because property names can be any string, if you want to access a property named “2” or “John Doe”, you must use square brackets: value[2] or value["John Doe"]. This is the case even though you know the precise name of the property in advance, because neither “2” nor “John Doe” is a valid variable name and so cannot be accessed through dot notation.

对于数组

数组中的元素存储在属性中。因为这些属性的名称都是数字,而且我们经常需要从变量中获取它们的名称,所以我们必须使用括号语法来访问它们。数组的length属性告诉我们它包含多少个元素。这个属性名是一个有效的变量名,我们事先知道它的名字,所以要找到一个数组的长度,你通常写array。长度,因为它比数组[" Length "]更容易写。

其他回答

点表示法总是可取的。如果你正在使用一些“更聪明的”IDE或文本编辑器,它将显示来自该对象的未定义名称。 只有当你的名字有破折号或类似无效的东西时,才使用括号符号。如果名称存储在变量中也一样。

foo。Bar和foo[" Bar "]访问foo上的属性,但不一定是相同的属性。区别在于如何解释bar。当使用点时,点后面的单词是属性的字面名称。使用方括号时,将计算方括号之间的表达式以获得属性名。而foo。Bar获取 属性的值名为"bar", foo["bar"]尝试计算表达式"bar"并使用转换为字符串的结果作为属性名

点表示法的局限性

如果我们拿这个物体:

const obj = {
  123: 'digit',
  123name: 'start with digit',
  name123: 'does not start with digit',
  $name: '$ sign',
  name-123: 'hyphen',
  NAME: 'upper case',
  name: 'lower case'
};

使用点符号访问它们的专有属性

obj.123;      // ❌ SyntaxError
obj.123name;  // ❌ SyntaxError
obj.name123;  // ✅ 'does not start with digit'
obj.$name;    // ✅  '$ sign'
obj.name-123;  // ❌ SyntaxError
obj.'name-123';// ❌ SyntaxError
obj.NAME; // ✅ 'upper case'
obj.name; // ✅ 'lower case'

但对于括号符号来说,这些都不是问题:

obj['123'];     // ✅ 'digit'
obj['123name']; // ✅ 'start with digit'
obj['name123']; // ✅ 'does not start with digit'
obj['$name'];   // ✅ '$ sign'
obj['name-123']; // ✅ 'does not start with digit'
obj['NAME']; // ✅ 'upper case'
obj['name']; // ✅ 'lower case'

使用variable访问变量:

const variable = 'name';
const obj = {
  name: 'value'
};
// Bracket Notation
obj[variable]; // ✅ 'value'
// Dot Notation
obj.variable; // undefined

或者当你想动态改变一个元素的classList动作时:

// Correct

showModal.forEach(node => {
  node.addEventListener(
    'click',
    () => {
      changeClass(findHidden, 'remove'); // Correct
    },
    true
  );
});

//correct
function changeClass(findHidden, className) {
  for (let item of findHidden) {
    console.log(item.classList[className]('hidden'));// Correct
  }
}

// Incorrect 
function changeClass(findHidden, className) {
  for (let item of findHidden) {
    console.log(item.classList.className('hidden')); // Doesn't work
  }
}

点表示法和括号表示法都用于在JavaScript中访问对象属性。点表示法是最常用的,因为它更容易阅读和理解。为什么我们要用括号,这两者有什么区别呢?好吧,方括号符号[]允许我们使用变量访问对象属性,因为它将方括号内的表达式转换为字符串。

Const person = { 名称:“约翰”, 年龄:30 }; / /点符号 const nameDot = person.name; console.log (nameDot); / /“约翰” const name括号= person['name']; console.log (nameBracket); / /“约翰”

现在,让我们看一个变量的例子:

Const person = { 名称:“约翰”, 年龄:30 }; const myName = 'name'; console.log(人[名字]); / /“约翰”

点表示法的另一个优点是只包含字母数字(以及_和$),例如,如果你想访问一个像下面这样的对象(包含'-',你必须使用括号表示法)

Const person = { my-name: John } console.log(人['我的名字']);/ /“约翰” / / console.log (person.my-name);/ /错误

我举了另一个例子来清楚地理解用法上的差异。当使用嵌套数组和嵌套对象时

    const myArray = [
  {
    type: "flowers",
    list: [ "a", "b", "c" ],
  },
  {
    type: "trees",
    list: [ "x", "y", "z" ],
  }
];

现在如果我们想要访问树列表中的第二项是y。

我们不能一直用括号

const secondTree = myArray[1]["list"][1]; // incorrect syntex

相反,我们必须使用

const secondTree = myArray[1].list[1]; // correct syntex