有这样一个需求,计算从N到M的总和,要实现这个需求并不困难,只是要看哪种方式更简洁,执行效率更快
简单的for循环
var sum = function (n, m) {
var t = 0;
for (;n <= m; n++) {
t += n;
}
return t;
}
console.log(sum(1, 10)) // Output: 55
while循环
var sum = function (n, m) {
var t = 0;
while (n <= m) {
t += n;
n++;
}
return t;
}
console.log(sum(1, 10)) // Output: 55
递归
var sum = function (n, m) {
if (m === n) {
return m;
}
return m + sum(n, m - 1)
}
console.log(sum(1, 10)) // Output: 55
但是,递归方法不能使用太多,因为递归特别耗内存,容易出
VM5541:2 Uncaught RangeError: Maximum call stack size exceeded
at sum (<anonymous>:2:20)
at sum (<anonymous>:6:14)
at sum (<anonymous>:6:14)
at sum (<anonymous>:6:14)
at sum (<anonymous>:6:14)
at sum (<anonymous>:6:14)
at sum (<anonymous>:6:14)
at sum (<anonymous>:6:14)
at sum (<anonymous>:6:14)
at sum (<anonymous>:6:14)
而for
和while
方式的遍历是最快的!