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

标签 javascript arrays object parentheses

过去我解决过类似下面这个问题,我通过将对象键分配给其当前值或 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() 方法返回数组的长度:

示例:

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] 被初始化为括号内的一个空数组如果需要,然后 Success 被插入其中。

示例:

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

关于javascript - 设置对象键 JavaScript 值时的括号位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384794/

相关文章:

javascript - 仅当外部更改时才触发 $watch

arrays - 在 Matlab 中存储固定大小和数据类型的多个图像的所有可能且内存有效的方法是什么?

reactjs - 在 ReactJS 中使用复杂对象的 useState 无法按预期工作

c# - 如何从另一种方法访问我的控件

javascript - Safari(Mac 和 iOS)不允许名为 "𝝙"的函数。这是否违反规范?

javascript - 如何降低长 bool 表达式的复杂性?

javascript - Typescript 生成 typescript 而不是 javascript

arrays - 提高阵列访问速度

python - 遍历 numpy 数组的最后一个轴

c++ - C++中获取特定函数名的字符串