过去我解决过类似下面这个问题,我通过将对象键分配给其当前值或 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/