题解 | #数组求和#

数组求和

https://www.nowcoder.com/practice/cc3ce199461c4c4cb8f63db61d7eba30

//写法一:for循环

let res=0;

for(let i=0;i<arr.length;i++){

res += arr[i]

}

return res

//写法二:reduce方法 :为数组的每个值(从左到右)执行提供的函数。函数的返回值存储在total中,total,currentValue都是必须值。

let res= arr.reduce(function(total,currentValue){

return total + currentValue

})

return res

//写法三:foreach方法:还可以使用JavaScript中的Array.prototype.forEachO方法来实现求和函数。forEachO方法会迭代数组中的每个元素,并将其与先前迭代的结果相加。

let res=0;

arr.forEach(function(item){

res +=item;

})

return res;

全部评论

相关推荐

05-22 09:23
门头沟学院 Java
点赞 评论 收藏
分享
苍蓝星上艾露:这简历。。。可以试试我写的开源简历优化工具https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-16 12:23
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务