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
posted @ 2022-07-14 16:39  zc-lee  阅读(115)  评论(0)    收藏  举报