当业务需要从一个数组里求出某项的和的时候.
1.for遍历
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var resulte = 0; for (let index = 0; index < a.length; index++) { resulte += a[index]; } console.log(resulte); //55
又或者会去这样实现
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var resulte = 0; a.forEach(i => resulte += i) console.log(resulte); //55
其实js的数组内置函数早已经帮我们实现好了
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const INITVAL = 0;//默认从0开始累加,可要可不要 var resulte = a.reduce((prev, item) => prev + item, INITVAL) console.log(resulte); //55
如何实现一个简单的reduce
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const INITVAL = 0;//默认从0开始累加,可要可不要 var resulte = a.reduce((prev, item) => prev + item, INITVAL) console.log(resulte); //55 ``` [reduce使用教程](https://www.runoob.com/jsref/jsref-reduce.html) ### 如何实现一个简单的reduce ``` Array.prototype.myReduce = function (cb, initVal) { var resulte = initVal; var len = this.length; var i = 0; //空数组不执行 if (len === 0) { return console.log('数组不能为空') } //initVal如果不为空,索引+1 if (initVal === undefined) { resulte = this[i] i = 1 } for (i; i < len; i++) { var item = this[i]; resulte = cb(resulte, item, i); } return resulte } var b = [1, 3, 4, 5, 6] var persons = [ { name: "张三", age: 18 }, { name: "李四", age: 36 } ] var agesum= persons.myReduce((a,c)=> a+c.age,0) var r = b.myReduce(function (pre, item, index) { console.log(pre, item, index); //上一个值, 遍历的当前项 , 索引 return pre + item }, 7) console.log(r); console.log(agesum);