JavaScript系列--JavaScript数组高阶函数reduce()方法详解及奇淫技巧 (2)

(5)对象里的属性求和

var result = [ { subject: 'math', score: 10 }, { subject: 'chinese', score: 20 }, { subject: 'english', score: 30 } ]; var sum = result.reduce(function(prev, cur) { return cur.score + prev; }, 0); console.log(sum) //60

 

(6)将[1,3,1,4]转为数字1314

function addDigitValue(prev,curr,curIndex,array){ var exponent = (array.length -1) -curIndex; var digitValue = curr*Math.pow(10,exponent); return prev + digitValue; } var arr6 = [1,3,1,4]; var result7 = arr6.reduce(addDigitValue,0) console.info('result7',result7)

 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpxyzy.html