记一次reduce的使用注意点

当数组等于1时,reduce里不会打印
var numbers = [{key:15.5}];

function getSum(total, num) {
    console.log('打印')
    return typeof(total) === 'number' ? total + Math.round(num.key):total.key + Math.round(num.key);
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
}

getSum里面的 console没有打印 reduce直接返回numbers 0索引整个元素对象
当数组长度大于1时,reduce里会打印
var numbers = [{key:15.5}, {key:2.3}, {key:1.1}];

function getSum(total, num) {
    console.log('打印')
    return typeof(total) === 'number' ? total + Math.round(num.key):total.key + Math.round(num.key);
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
}

个人博客主页 www.chrischen.cn

点赞