我无法使用forEach获得所需的结果。假设下面的代码产生所期望的结果:ForEach内功能JavaScript
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
'evenNum.push(CurrentValue的);' – Keith
要使用括号标记使用当前迭代withing'.forEach的索引()''回调array.forEach(功能(CurrentValue的,索引){ 如果(CurrentValue的%2 === 0) evenNum.push(array [index]); })' – guest271314
因为最后两个'currentValue'超出了数组范围,所以不要提''[10,10,10]'而是'[10,undefined,undefined]'。 – Lixus