-
-
Notifications
You must be signed in to change notification settings - Fork 241
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
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));
} |
let arr = [1, 2, 3, 4, 5];
let sum = 0;
arr.forEach(function(item) {
sum += item;
});
console.log(sum); // 输出: 15
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue,0);
console.log(sum); // 输出:15
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: