JS Array 快速求和

Array求和用for那些感觉太麻烦了,代码不好看,想了想用reduce可以更加简洁一点,记录 

const array=[1,2,3]
console.log(array.reduce((a,b)=>a+b)) //6

JS Array 快速求和_第1张图片

reduce 方法的简介 

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

如果报错 Reduce of empty array with no initial value 
参考我这篇Blog https://blog.csdn.net/Damien_J_Scott/article/details/130080795?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22130080795%22%2C%22source%22%3A%22Damien_J_Scott%22%7D

你可能感兴趣的:(JS&TS,javascript,开发语言,ecmascript)