我無法使用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