当前位置:网站首页>js数组求和的5种方法
js数组求和的5种方法
2022-06-24 09:50:00 【燕穗子博客】
目录
计算给定数组 arr 中所有元素的总和
sum([ 1, 2, 3, 4 ])1、不考虑算法复杂度,用递归做:
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、常规循环
function sum(arr) {
var s = 0;
for (var i=arr.length-1; i>=0; i--) {
s += arr[i];
}
return s;
}3、函数式编程 map-reduce
function sum(arr) {
return arr.reduce(function(prev, curr, idx, arr){
return prev + curr;
});
}4、forEach遍历
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("+"));
};边栏推荐
- 【数据分析数据源】全国各省市行政区坐标(包含边界坐标点和中心坐标点)
- uniapp开发微信小程序,显示地图功能,且点击后打开高德或腾讯地图。
- numpy. logical_ and()
- 顺丰科技智慧物流校园技术挑战赛(2022/06/19)【AK】
- 希尔排序图文详解+代码实现
- 1. project environment construction
- 【资源分享】2022年第五届土木,建筑与环境工程国际会议(ICCAEE 2022)
- Resolved: methods with the same name as their class will not be constructors in
- Spark submission parameter -- use of files
- International Symposium on energy and environmental engineering in 2022 (coeee 2022)
猜你喜欢

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

5. dish management business development

2022全网最全最细的jmeter接口测试教程以及接口测试流程详解— JMeter测试计划元件(线程<用户>)

3.员工的增删改查

The difference between the sleep () method and the wait () method of a thread

Petit guide de construction rapide du bras mécanique (II): application du bras mécanique

3. addition, deletion, modification and query of employees

Thread operation principle

Status of the thread pool

24. 图像拼接大作业
随机推荐
1. project environment construction
线程池的执行流程
How to use multiple kindeditor editors on a page and pass values to the server
Petit guide de construction rapide du bras mécanique (II): application du bras mécanique
leetCode-223: 矩形面积
Machine learning perceptron and k-nearest neighbor
2022全网最全最细的jmeter接口测试教程以及接口测试流程详解— JMeter测试计划元件(线程<用户>)
Quick completion guide for mechanical arm (I): development overview of mechanical arm
uniapp实现禁止video拖拽快进
cuda runtime error (801) : Raw out
用扫描的方法分发书稿校样
【IEEE出版】2022年服务机器人国际研讨会(IWoSR 2022)
tf. contrib. layers. batch_ norm
leetCode-1051: 高度检查器
[EI分享] 2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)
分布式事务原理以及解决分布式事务方案
牛客-TOP101-BM28
Web site development, lazy image loading
24. 图像拼接大作业
leetCode-2221: 数组的三角和