为什么 a.push(b)
在我的 Array.reduce() 中不起作用? a=a.push(b)
其中 b
是字符串,将 a
转换为整数。?!
getHighestValuesInFrequency: function(frequency) {
//Input:var frequency = {mats: 1,john: 3,johan: 2,jacob: 3};
//Output should become ['John','jacob']
var objKeys = Object.keys(frequency);
var highestVal = objKeys.reduce((a,b)=>
{highestVal = (frequency[b] > a)? frequency[b] : a;
return highestVal;},0);
var winner = objKeys.reduce((a,b)=>
{ a = (frequency[b] === highestVal)? a.push(b) : a;
return a},[]);
return winner;
}
最佳答案
由于 push()
返回数组的新长度,您将长度分配给 a
。使用 if
语句代替条件运算符。
var winner = objKeys.reduce((a, b) => {
if (frequency[b] === highestVal) {
a.push(b);
}
return a;
}, []);
关于javascript - push() 不会在 reduce() 中按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32722435/