当前位置:网站首页>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("+"));
};边栏推荐
- 包装类型的缓存机制
- [ei sharing] the 6th International Conference on ship, ocean and Maritime Engineering in 2022 (naome 2022)
- Web project deployment
- 88.合并有序数组
- The difference between static link library and dynamic link library
- Niuke-top101-bm29
- Appium automation test foundation - mobile end test environment construction (I)
- 用扫描的方法分发书稿校样
- How to use multiple kindeditor editors on a page and pass values to the server
- pycharm快捷键大全
猜你喜欢

【资源分享】2022年环境工程与生物技术国际会议(CoEEB 2022)

希尔排序图文详解+代码实现

Quick completion guide for mechanical arm (I): development overview of mechanical arm

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

JMeter interface test tool foundation - badboy tool

Practice sharing of packet capturing tool Charles

Quick completion guide for manipulator (III): mechanical structure of manipulator

Baidu online disk download has been in the process of requesting solutions

JMeter接口测试工具基础 — Badboy工具

Outils de capture de paquets
随机推荐
leetCode-1823: 找出游戏的获胜者
Flink checkPoint和SavePoint
Baidu online disk download has been in the process of requesting solutions
【Energy Reports期刊发表】2022年能源与环境工程国际会议(CFEEE 2022)
Six states of threads
Quick completion guide for manipulator (III): mechanical structure of manipulator
Quick completion guide for mechanical arm (zero): main contents and analysis methods of the guide
Difference between package type and basic type
Normal equation
2.登陆退出功能开发
HBuilder制作英雄皮肤抽奖小游戏
How to use multiple kindeditor editors on a page and pass values to the server
Multithreaded applications - improve efficiency
2022 the most complete and detailed JMeter interface test tutorial and detailed interface test process in the whole network - JMeter test plan component (thread < user >)
【IEEE出版】2022年工业自动化,机器人与控制工程国际会议(IARCE 2022)
[EI分享] 2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)
leetCode-498: 對角線遍曆
5.菜品管理业务开发
JMeter interface test tool foundation - badboy tool
Petit guide de construction rapide du bras mécanique (II): application du bras mécanique