当前位置:网站首页>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("+"));
};边栏推荐
- 牛客-TOP101-BM28
- A method to solve the self-adaptive width and height of the internal picture of rich text label in wechat applet
- uniapp实现禁止video拖拽快进
- 【IEEE出版】2022年服务机器人国际研讨会(IWoSR 2022)
- JMeter interface test tool foundation - sampler (II)
- The difference between the sleep () method and the wait () method of a thread
- 机械臂速成小指南(三):机械臂的机械结构
- cuda runtime error (801) : Raw out
- Learn to use PHP to implement unlimited comments and unlimited to secondary comments solutions
- uniapp开发微信小程序,显示地图功能,且点击后打开高德或腾讯地图。
猜你喜欢

Uniapp implements the function of clicking to make a call

3.员工的增删改查

【数据分析数据源】全国各省市行政区坐标(包含边界坐标点和中心坐标点)

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

JMeter接口测试工具基础— 取样器sampler(二)

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

Machine learning - principal component analysis (PCA)

283.移动零

leetCode-498: 對角線遍曆

Six states of threads
随机推荐
用扫描的方法分发书稿校样
4.分类管理业务开发
leetCode-面试题 16.06: 最小差
JMeter interface test tool foundation - badboy tool
顺丰科技智慧物流校园技术挑战赛(2022/06/19)【AK】
Cross domain overview, simple accumulation
283. move zero
Learn to use the phpstripslush function to remove backslashes
【数据分析数据源】全国各省市行政区坐标(包含边界坐标点和中心坐标点)
进程与多线程
charles抓包工具使用教程
Process and multithreading
Leetcode-223: rectangular area
Leetcode-2221: triangular sum of arrays
leetCode-1051: 高度检查器
Baidu online disk download has been in the process of requesting solutions
[IEEE publication] 2022 International Conference on service robots (iwosr 2022)
牛客-TOP101-BM29
2022全网最全最细的jmeter接口测试教程以及接口测试流程详解— JMeter测试计划元件(线程<用户>)
How to use multiple kindeditor editors on a page and pass values to the server