美文网首页前端
Array.prototype.reduce()的用法

Array.prototype.reduce()的用法

作者: 风起云帆 | 来源:发表于2017-11-16 08:27 被阅读0次

Array的reduce()把一个函数作用在这个Array的[x1, x2, x3...]上,这个函数必须接收两个参数,reduce()把结果继续和序列的下一个元素做累积计算

其效果就是:

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)

比方说对一个Array求和,就可以用reduce实现:

var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
    return x + y;
}); // 25

利用reduce()求积:

'use strict';

function product(arr) {
  return arr.reduce(function(x, y){
    return x*y;
})  
}

// 测试:
if (product([1, 2, 3, 4]) === 24 && product([0, 1, 2]) === 0 && product([99, 88, 77, 66]) === 44274384) {
    console.log('测试通过!');
}
else {
    console.log('测试失败!');
}

...后期遇到好的例子再放进来!

相关文章

网友评论

    本文标题:Array.prototype.reduce()的用法

    本文链接:https://www.haomeiwen.com/subject/urikvxtx.html