从对象的键中获得最大的价值

时间:2019-12-08 23:04:34

标签: javascript

我具有此功能:

var majorityElement = function(nums) {
    let count = {}

    for(i=0; i < nums.length; i++){
        let x = nums[i];
        count[x] ? count[x] + 1 : count[x] = 1
    }

    console.log(count)
    return Object.keys(count).reduce((a,b) => count[a] > count[b] ? a : b)
};

因此,我不明白为什么计数不能真正起作用,如果运行该计数,则此数组[3,3,4]看起来像这样:

count{
   3: 1
   4: 1
}

不是3:2和4:1吗?

1 个答案:

答案 0 :(得分:2)

作业应位于左侧,而不是:

count[x] ? count[x] + 1 : count[x] = 1

尝试:

count[x] = count[x] ? (count[x] + 1) : 1

var majorityElement = function(nums) {
    let count = {}

    for(i=0; i < nums.length; i++){
        let x = nums[i];
        count[x] = count[x] ? (count[x] + 1) : 1
    }

    console.log(count)
    return Object.keys(count).reduce((a,b) => count[a] > count[b] ? a : b)
};

console.log(majorityElement([3,3,4]))