是否有一个JavaScript相当于Clojure的“减少”功能或Python的itertools.accumulate
?换句话说,给定的阵列[x_0, x_1, x_2 ... x_n-1]
和一个函数f(prev, next)
,它将返回长度n
的阵列与值:JavaScript相当于Clojure的“减少”或Python的itertools.accumulate
[x_0, f(x_0, x_1), f(f(x_0, x_1), x_2)... f(f(f(...)), x_n)]
我模拟低于所期望的行为:
function accumsum(prev, next) {
last = prev[prev.length - 1] || 0;
prev.push(last + next);
return prev;
}
var x = [1, 1, 1, 1];
var y = x.reduce(accumsum, []);
var z = y.reduce(accumsum, []);
console.log(x);
console.log(y);
console.log(z);
其显示:
[ 1, 1, 1, 1 ]
[ 1, 2, 3, 4 ]
[ 1, 3, 6, 10 ]
但我想知道是否有办法写somet更简单就像
[1, 1, 1, 1].reductions(function(prev, next) {return prev + next;});
如果不是,有没有比我写的更习惯的方式来做到这一点在JavaScript?
如果你不'不介意的图书馆,看看[Underscore](http://underscorejs.org/)它有一个reduce函数,它应该完成你想要做的事情 – jcern
@jcern:这不是一个简单的减少(和普通的JS现在'减少',除非你有t o支持unmentionables)。 – Amadan
再次与图书馆,[拉姆达](http://ramdajs.com)(披露:我是作者)有['扫描'](http://ramdajs.com/docs/#scan)和[' mapAccum'](http://ramdajs.com/docs/#mapAccum),它以这种方式工作。 –