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

在代码:

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

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

// vs. 
var x = foo.bar;

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


当前回答

让我再添加一些方括号符号的用例。如果你想访问一个属性,比如对象中的x-proxy,那么-将被错误地解释。还有一些其他的情况,比如空格,点,等等,点运算对你没有帮助。另外,如果你在一个变量中有键,那么在一个对象中访问键值的唯一方法是用括号符号。希望你能了解更多的背景。

其他回答

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 "]更容易写。

括号表示法可以使用变量,所以它在两个点表示法不起作用的情况下很有用:

1)动态确定属性名时(直到运行时才知道确切的名称)。

2)当使用for..in循环遍历对象的所有属性时。

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

当-时必须使用方括号

属性名是number。 Var ob = { 1:“一个”, 7:“7” } ob.7 // SyntaxError ob[7] // " 7 " 属性名有特殊字符。 Var ob = { 'This is one': 1, 这是7:7, } ob.'This is one' // SyntaxError ob['这是一个']// 1 属性名被赋给一个变量,您要访问 属性值。 Var ob = { “一”:1、 “七”:7, } var _Seven = ' 7 '; b. _seven //未定义 ob[_Seven] // 7 .使用实例

或者当你想动态改变一个元素的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
  }
}

如果属性名有特殊字符,则需要使用括号:

var foo = {
    "Hello, world!": true,
}
foo["Hello, world!"] = false;

除此之外,我想这只是个人喜好的问题。恕我直言,点表示法更短,而且更明显地表明它是一个属性而不是数组元素(当然JavaScript没有关联数组)。