Javascript forEach循环

时间:2016-03-10 20:22:35

标签: javascript foreach

尝试使此功能成为现实。我认为问题出在我的for循环中。

function forEach(array, callback){    
    console.log(array, callback);
    for(var i = 0; i < array.length; i++) {

    }
}

 // testing your code with console.assert
var total = 1;
var myArray = [1, 2, 3, 4];
function multiplyTotal(a) {
    total *= a;
}
forEach(myArray, multiplyTotal);
// and finally assert; if this fails, the program stops
console.assert(total === 24);

2 个答案:

答案 0 :(得分:2)

function forEach(array, callback){    
    console.log(array, callback);
    for(var i = 0; i < array.length; i++) {
       callback(array[i]); // you need to call callback function
    }
}

答案 1 :(得分:0)

此外,Javascript已经具有内置功能:

myArray.forEach(multiplyTotal);

http://www.w3schools.com/jsref/jsref_forEach.asp