push()无法在reduce()中按预期方式工作 [英] push() won't work as expected in reduce()
本文介绍了push()无法在reduce()中按预期方式工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 a.push(b)
在我的 Array.reduce()中不起作用?a = a.push(b)
,其中 b
是一个字符串,将 a
转换为整数.
Why doesn't a.push(b)
work in my Array.reduce()? a=a.push(b)
where b
is a string, turns a
to an integer.?!
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
语句.
Since push()
returns the new length of the array, you're assigning the length to a
. Instead of a conditional operator, use an if
statement.
var winner = objKeys.reduce((a, b) => {
if (frequency[b] === highestVal) {
a.push(b);
}
return a;
}, []);
这篇关于push()无法在reduce()中按预期方式工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文