我无法使用forEach获得所需的结果。假设以下代码产生了所需的结果:
function isEven(array) {
var evenNum = [];
for (var i = 0; i <= array.length; i++) {
if (array[i] % 2 === 0)
evenNum.push((array[i]));
}
return evenNum;
}
var output = isEven([1, 4, 5, 6, 10, 13]);
console.log(output); // --> [4, 6, 10]
// How do I get the same result with a forEach method?
// My code reads:
function isEven(array) {
var evenNum = [];
array.forEach(function (currentValue) {
if (currentValue % 2 === 0)
evenNum.push(array[currentValue]);
})
return evenNum;
}
var output = isEven([1, 4, 5, 6, 10, 13]);
console.log(output); // --> [10, 10, 10] not desired
答案 0 :(得分:2)
var numbers = [1,2,3,4,5,6,7,8,9,10];
var even;
For loop:
even = [];
for (var i = 0; i < numbers.length; ++i)
if (numbers[i] % 2 === 0)
even.push(numbers[i]);
console.log(even);
使用forEach:
even = [];
numbers.forEach(n => {
if (n % 2 === 0)
even.push(n);
});
console.log(even);
或者更简洁:
even = numbers.filter(n => (n % 2 === 0));
console.log(even);
答案 1 :(得分:1)
当你应该直接使用currentValue
时,看起来你正在索引数组。
function isEven(array){
var evenNum = [];
array.forEach(function(currentValue){
if(currentValue % 2 === 0)
evenNum.push(currentValue);
})
return evenNum;
}
答案 2 :(得分:1)
你有evenNum.push(array[currentValue])
。它应该是evenNum.push(currentValue)
。
function isEven(array) {
var evenNum = [];
array.forEach(function (currentValue) {
if (currentValue % 2 === 0)
evenNum.push(currentValue);
})
return evenNum;
}
var output = isEven([1, 4, 5, 6, 10, 13]);
console.log(output); // --> [10, 10, 10] not desired