Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

不用循环求和 #108

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments
Open

不用循环求和 #108

Sunny-117 opened this issue Nov 3, 2022 · 5 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@yang-xianzhu
Copy link

yang-xianzhu commented Nov 11, 2022

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)

@bearki99
Copy link

const arr = [1, 3, 5, 4, 3];
const res = arr.reduce((prev, next)=>prev+next, 0);

console.log(res);

@woailllljjjj
Copy link

woailllljjjj commented Feb 17, 2023

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])

@veneno-o
Copy link
Contributor

function main(args){
    const len = args.length;
    if(len === 0){
        return 0;
    }
    return args[0] + main(args.slice(1));
}

@kangkang123269
Copy link

  1. forEach方法
let arr = [1, 2, 3, 4, 5];
let sum = 0;
arr.forEach(function(item) {
    sum += item;
});
console.log(sum); // 输出: 15
  1. reduce
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue,0);
console.log(sum); // 输出:15
  1. eval函数
let arr = [1,2,3 ,4 ,5];
let sum = eval(arr.join("+"));
console.log(sum); // 输出:15 
  1. 递归
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants