我可以使用if和for语句iside map方法

时间:2019-05-08 13:02:31

标签: javascript

我正在尝试将以下代码与map或filter方法一起使用 是否可以这样做:

function doubleOddNumbers(numbers) {
  const newNumbers = [];
  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 !== 0) {
      newNumbers.push(numbers[i] * 2);
    }
  }
  return newNumbers;
}

const myNumbers = [1, 2, 3, 4];
console.log(doubleOddNumbers(myNumbers);

// Do not change or remove anything below this line
module.exports = {
  myNumbers,
  doubleOddNumbers,
};

2 个答案:

答案 0 :(得分:1)

您可以filter个奇数,然后使用map返回doubled值

function doubleOddNumbers(numbers) {
  return numbers.filter(n => n % 2).map(n => n * 2)
}

/* This would also work
function doubleOddNumbers(numbers) {
  return numbers.reduce((r, n) => n % 2 ? r.concat(n * 2) : r, [])
}
*/
const myNumbers = [1, 2, 3, 4];
console.log(doubleOddNumbers(myNumbers));

答案 1 :(得分:-1)

使用减少

function doubleOddNumbers(numbers) {
  return numbers.reduce((allNumbers, number) => {
    if (number % 2 === 1) {
      allNumbers.push(number * 2);
    }
    return allNumbers;
  }, []);
}