当前位置:网站首页>Five methods of JS array summation
Five methods of JS array summation
2022-06-24 10:37:00 【Yansuizi blog】
Catalog
1、 Regardless of algorithm complexity , Do with recursion :
3、 Functional programming map-reduce
Compute a given array arr The sum of all the elements in
sum([ 1, 2, 3, 4 ])1、 Regardless of algorithm complexity , Do with recursion :
function sum(arr) {
var len = arr.length;
if(len == 0){
return 0;
} else if (len == 1){
return arr[0];
} else {
return arr[0] + sum(arr.slice(1));
}
}2、 Conventional circulation
function sum(arr) {
var s = 0;
for (var i=arr.length-1; i>=0; i--) {
s += arr[i];
}
return s;
}3、 Functional programming map-reduce
function sum(arr) {
return arr.reduce(function(prev, curr, idx, arr){
return prev + curr;
});
}4、forEach Traverse
function sum(arr) {
var s = 0;
arr.forEach(function(val, idx, arr) {
s += val;
}, 0);
return s;
};5、eval
function sum(arr) {
return eval(arr.join("+"));
};边栏推荐
- Leetcode - 498: traversée diagonale
- 【Energy Reports期刊发表】2022年能源与环境工程国际会议(CFEEE 2022)
- [EI分享] 2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)
- Thread operation principle
- 88.合并有序数组
- 283.移动零
- cuda runtime error (801) : Raw out
- Cross domain overview, simple accumulation
- How to customize sharing links in wechat for H5 web pages
- 126. 单词接龙 II BFS
猜你喜欢

Machine learning - principal component analysis (PCA)

2022 International Symposium on intelligent robots and systems (isoirs 2022)

进程与多线程

线程的 sleep() 方法与 wait() 方法的区别

283.移动零

图解杂项【防止丢失进行存档用的】

机械臂速成小指南(一):机械臂发展概况

Appium automation test foundation - mobile end test environment construction (I)

Leetcode-498: diagonal traversal

Quick completion guide for mechanical arm (I): development overview of mechanical arm
随机推荐
Solve the timeout of Phoenix query of dbeaver SQL client connection
leetCode-面试题 16.06: 最小差
3. addition, deletion, modification and query of employees
tf. errors
Leetcode-929: unique email address
2022年能源与环境工程国际研讨会(CoEEE 2022)
cuda runtime error (801) : Raw out
分布式系统你必须了解的点-CAP
The difference between static link library and dynamic link library
Leetcode-2221: triangular sum of arrays
Leetcode-1051: height checker
多线程的应用 - 提升效率
88.合并有序数组
Web project deployment
Role of message queuing
Status of the thread pool
Leetcode-498: diagonal traversal
抓包工具charles实践分享
Normal equation
Safety and food security for teachers and students of the trapped Yingxi middle school