js - 数组求和
js - 数组求和
原型对象扩展内置对象方法(即给Array增加方法)
Array.prototype.sum = function () {
var sum = 0;
for (var i = 0; i < this.length; i++) {
sum += this[i];
}
return sum;
};
var arr = [1, 2, 3, 4];
console.log(arr.sum()); // 10
普通for循环函数求和
<script>
function sum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
var arr = [1, 2, 3, 4];
console.log(sum(arr)); // 10
递归
function sum(arr) {
if (arr.length == 0) {
return 0; // 递归出口
} else {
return arr[0] + sum(arr.slice(1));
}
}
var arr = [1, 2, 3, 4];
console.log(sum(arr)); // 10
reduce
function sum(arr) {
return arr.reduce(function (total, value) {
return total + value;
}, 0);
}
var arr = [1, 2, 3, 4];
console.log(sum(arr)); // 10
forEach遍历
function sum(arr) {
var s = 0;
arr.forEach(function (value) {
s += value;
});
return s;
}
var arr = [1, 2, 3, 4];
console.log(sum(arr)); // 10
eval()方法
function sum(arr) {
return eval(arr.join("+"));
}
var arr = [1, 2, 3, 4];
console.log(sum(arr)); // 10
Lee2

浙公网安备 33010602011771号