我有一个长度约1000的数组。为什么地图函数在某些索引中返回未定义?有没有办法只返回满足此条件的数组?我想返回一个值> 0的数组。

 var total_percents = cars.map(function(element) {
        var savings_percent = Number(element[0].getAttribute("percent-savings"));
        if (savings_percent > 0)
            return savings_percent;
});

最佳答案

不确定您要完成什么,但是:

尝试这样的操作以返回所有pctSavings的总和:

const totalPercents = cars.reduce((sum, el) => {
    const pctSavings = +(el[0].getAttribute("percent-savings"));
    if (pctSavings > 0) sum += pctSavings;
    return sum;
}, 0);


要返回pctSavings数组,只需执行以下操作:

const totalPercents = cars.reduce((arr, el) => {
    const pctSavings = +(el[0].getAttribute("percent-savings"));
    if (pctSavings > 0) arr.push(pctSavings);
    return arr;
}, []);


要获得最大的pctSavings,请执行以下操作:

let maxPctSavings = 0;
cars.forEach(el => {
    const pctSavings = +(el[0].getAttribute("percent-savings"));
    if (pctSavings > maxPctSavings) maxPctSavings = pctSavings
});
console.log(maxPctSavings) // this is your answer

09-30 16:59