我有一个对象数组:

var myArr = [{
    number: 5,
    shouldBeCounted: true
}, {
    number: 6,
    shouldBeCounted: true
}, {
    number: 7,
    shouldBeCounted: false
}, ...];


如何为number设置为shouldBeCounted的对象查找max true?我不想使用循环,只是想知道使用Math.max.apply(或类似的东西)是否可行。

最佳答案

不,这不可能。您可以将Math.max.map一起使用



var myArr = [{
    number: 5,
    shouldBeCounted: true
}, {
    number: 6,
    shouldBeCounted: true
}, {
    number: 7,
    shouldBeCounted: false
}];


var max = Math.max.apply(Math, myArr.map(function (el) {
    if (el.shouldBeCounted) {
        return el.number;
    }

    return -Infinity;
}));

console.log(max);

关于javascript - 在JS中获取已过滤对象数组的最大值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30054677/

10-09 14:30