Methods for summing JavaScript arrays: 1. for loop, the code is [for (var i = 0; i
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
Methods for summing JavaScript arrays:
1. for loop
var sum = 0; console.time("for"); for (var i = 0; i < arr.length; i++) { sum += arr[i]; } console.timeEnd("for"); console.log(sum);
2. while loop
var sum = 0; function getSum(item, index, array) { sum += item; } console.time(); arr.forEach(getSum); console.timeEnd(); console.log(sum);
3. some method
var sum = 0; function getSum(item, index, array) { sum += item; } console.time(); arr.some(getSum); console.timeEnd(); console.log(sum);
var sum = 0; function getSum(item, index, array) { sum += item; } console.time(); arr.map(getSum); console.timeEnd(); console.log(sum);
var sum = 0; function getSum(item, index, array) { sum += item; } console.time(); arr.filter(getSum); console.timeEnd(); console.log(sum);
Related free learning recommendations: javascript video tutorial
The above is the detailed content of How to sum arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!