var addition = [];addition.push(2);addition.push(3);
var total = 0;for (var i = 0; i < addition.length; i++){total += addition[i];}alert(total); // Just to output an example/* console.log(total); // Just to output an example with Firebug */
var array = [1, 2, 3];
for (var i = 0, sum = 0; i < array.length; sum += array[i++]);
JavaScript不知道块范围,所以sum是可访问的:
console.log(sum); // => 6
与上面相同,但是注释和准备为一个简单的函数:
function sumArray(array) {for (varindex = 0, // The iteratorlength = array.length, // Cache the array lengthsum = 0; // The total amountindex < length; // The "for"-loop conditionsum += array[index++] // Add number on each iteration);return sum;}
const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);console.log(sum); // 6
对于较旧的JS:
const sum = [1, 2, 3].reduce(add, 0); // with initial value to avoid when the array is empty
function add(accumulator, a) {return accumulator + a;}
console.log(sum); // 6
console.log(["hi", 1, 2, "frog"].reduce((a, b) => a + b))
let numOr0 = n => isNaN(n) ? 0 : n
console.log(["hi", 1, 2, "frog"].reduce((a, b) =>numOr0(a) + numOr0(b)))
console.log(eval([1,2,3].join('+')))
//This way is dangerous if the array is built// from user input as it may be exploited eg:
eval([1,"2;alert('Malicious code!')"].join('+'))
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(function(e){sum += e}); sum10> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(e => sum += e); sum10> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e in a) sum += e; sum"00123foobar"> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e of a) sum += e; sum10
let array = [1, 2, 3, 4]
function sum(...numbers) {let total = 0;for (const number of numbers) {total += number;}return total;}
console.log(sum(...array));
arr=[.6,9,.1,.1,.1,.1]
sum = arr.reduce((a,c)=>a+c,0)sortSum = [...arr].sort((a,b)=>a-b).reduce((a,c)=>a+c,0)
console.log('sum: ',sum);console.log('sortSum:',sortSum);console.log('sum==sortSum :', sum==sortSum);
// we use .sort((a,b)=>a-b) instead .sort() because// that second one treat elements like strings (so in wrong way)// e.g [1,10,9,20,93].sort() --> [1, 10, 20, 9, 93]