设置对象键值时的括号位置 JavaScript

Parentheses placement when setting value of object key JavaScript

过去我已经解决了像下面这个问题这样的问题,我通过将对象键分配给它的当前值或 0 然后在每次出现该字母时加 1 来计算一个字母在字符串中出现的次数再次。请参阅我在下面引用的行。

var letterCount = function(str) {
  noPuncStr = str.replace(/[^a-z]/ig, "")
  // noPuncStr = str.replace(/[^\w]/ig, "") //same thing except underscores would be allowed
  // console.log(noPuncStr);
  var result = {};
  for (var i = 0; i < noPuncStr.length; i++) {
    result[noPuncStr[i]] = (result[noPuncStr[i]] || 0) + 1 //THIS LINE. I set the key to its current value if truthy or 0 then add 1
  }
  return result;
}

console.log(letterCount("a%b& c*da"));

我刚刚完成了一个类似的问题,我试图做同样的事情,除了我想为自己设置一个键或一个空数组,如果错误,然后将当前值推送到键的结果.然而,当我这样做时,我得到了一个 TypeError: (result[value] || []).push is not a function。基于查看该问题的其他答案,我意识到我可以通过将括号放在该行的左端而不是像我在上面的 letterCount 问题中所做的那样将它放在 = 之后来解决它。为什么会这样?为了更好地说明我所说的正确解决方案和我所指的行如下。

Array.prototype.groupBy = function(fn) {
  var result = {};
  if (arguments.length === 0) {
    this.forEach(function(value){
      (result[value] = result[value] || []).push(value); /*WHY is the (
   all the way on the left of the line instead of after the equals sign
   like in letterCount?*/
    })
    return result;
  } else {
    this.forEach(function(value){
      (result[fn(value)] = result[fn(value)] || []).push(value);
    })
    return result;
  }
}

如有任何帮助,我将不胜感激!

push()方法returns数组长度:

示例:

var a = ['a', 'b', 'c'];
console.log(a.push('d'));  //4

如果你这样放置括号:

result[value] = (result[value] || []).push('Hmm);

…那么result[value]就简单的变成了数组的长度,这不是你想要的。

示例:

var result = {},
    value = 'v';
    
result[value] = (result[value] || []).push('Hmm');
console.log(result[value]);  //1

像这样放置括号:

(result[value] = result[value] || []).push('Success');

result[value]初始化为一个空数组if needed在括号内,然后Success被推入其中

示例:

var result = {},
    value = 'v';
    
(result[value] = result[value] || []).push('Success');
console.log(result[value]);  //Success