为什么JS Map函数返回未定义?

时间:2018-05-11 00:17:18

标签: javascript jquery arrays

我有一个长度约为1000的数组。为什么map函数在某些索引中返回undefined?有没有办法只返回满足这个条件的数组?我想要返回一个值为>的数组。 0

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

3 个答案:

答案 0 :(得分:2)

您需要在映射后过滤值,您可以使用filter数组方法对car => car > 0

这样的谓词进行过滤
var total_percents = cars.map((element) => Number(element[0].getAttribute("percent-savings"))).filter(car => car > 0)

您也可以使用reduce方法同时合并两个操作:



var total_percents =
  cars.reduce((acc, element) => {
    const percentSavings = Number(element[0].getAttribute("percent-savings"));

    if (percentSavings > 0) {
      acc.push(percentSavings);
    }

    return acc;
  }, [])




答案 1 :(得分:1)

不确定您尝试完成的任务,但是:

尝试这样的方法来返回所有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;
}, []);

要获得max 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

答案 2 :(得分:1)

使用reduce来过滤和映射值(应该比单独的filtermap更快且使用更少的内存)

var total_percents = cars.reduce(
  function(out, element) {
    var savings_percent = Number(element[0].getAttribute("percent-savings"));
    if (savings_percent > 0) {
      // Only add to the out-array if value is greater than 0.
      out.push(savings_percent);
    }
    return out;
  },
  [] // start with empty array
);

total_percents将是一个数组,其值大于0.

从另一个答案的评论中读到,你想要的是最大的节省。 然后我会这样做:

var max_savings = cars.reduce(
  function(value, element) {
    var savings_percent = Number(element[0].getAttribute("percent-savings"));
    return Math.max(savings_percent, value)
  },
  0 // start with no savings
);