不用循环求和
Sunny-117 opened this issue · comments
不用循环求和
const arr = []
// 求0~100000的和
for(let i =0;i<=100000;i++){arr.push(i)}
function getSum(arr){
return (arr[0] + arr[arr.length-1]) * arr.length / 2
}
const sum = getSum(arr)
console.log(sum)
const arr = [1, 3, 5, 4, 3];
const res = arr.reduce((prev, next)=>prev+next, 0);
console.log(res);
function totalNumber(arr) {
if(!arr || Object.prototype.toString.call(arr) !== '[object Array]' || arr.length === 0) {
throw new Error('参数必须是数组,且不允许为空')
}
const first = arr.splice(0,1)[0]
if(arr[0]) {
arr[0] += first
return totalNumber(arr)
}else {
return first
}
}
totalNumber([0,3,1,6])
function main(args){
const len = args.length;
if(len === 0){
return 0;
}
return args[0] + main(args.slice(1));
}
- forEach方法
let arr = [1, 2, 3, 4, 5];
let sum = 0;
arr.forEach(function(item) {
sum += item;
});
console.log(sum); // 输出: 15
- reduce
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue,0);
console.log(sum); // 输出:15
- eval函数
let arr = [1,2,3 ,4 ,5];
let sum = eval(arr.join("+"));
console.log(sum); // 输出:15
- 递归
function sumArray(arr) {
if (arr.length === 0) { // 基线条件:如果数组为空,那么总和就是0
return 0;
} else {
return arr[0] + sumArray(arr.slice(1)); // 递归步骤:取数组的第一个元素并加上对剩余部分调用sumArray函数的结果
}
}
let arr = [1, 2, 3, 4, 5];
console.log(sumArray(arr)); // 输出:15