为什么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/

10-12 01:01