2017-10-18 62 views
-2

我无法使用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 
+8

'evenNum.push(CurrentValue的);' – Keith

+1

要使用括号标记使用当前迭代withing'.forEach的索引()''回调array.forEach(功能(CurrentValue的,索引){ 如果(CurrentValue的%2 === 0) evenNum.push(array [index]); })' – guest271314

+1

因为最后两个'currentValue'超出了数组范围,所以不要提''[10,10,10]'而是'[10,undefined,undefined]'。 – Lixus

回答

1

它看起来像您正在索引到阵列中时,你应该直接使用currentValue

function isEven(array){ 
    var evenNum = []; 
    array.forEach(function(currentValue){ 
     if(currentValue % 2 === 0) 
     evenNum.push(currentValue); 
    }) 
    return evenNum; 
} 
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

2
var numbers = [1,2,3,4,5,6,7,8,9,10]; 
var even; 

For循环:

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);