Underscore.js _.iterators.accumulateWithReturn() 方法
在_.iterators.accumulateWithReturn()方法的帮助下,我们可以期望在调用迭代器函数时返回一个数组中的两个值,使用该方法将当前迭代的输出传递给下一个迭代值。
句法:
_.iterators.accumulateWithReturn(iter, binaryFn, initial)
返回:将数组中的两个值返回给迭代器。
示例 1:
在这个例子中,我们可以看到,通过使用_.iterators.accumulateWithReturn()方法,我们可以在调用迭代器时期望数组中的两个值。它总是将当前迭代的结果传递给下一个迭代。
// Defining underscore contrib variable
var _ = require('underscore-contrib');
var iter = _.iterators.List(["Geeks", "for", "Geeks"]);
function calculateLength(geeky, element) {
return [element.length, 'Length of '+element+'is '+element.length];
}
var gfg = _.iterators.accumulate(iter, calculateLength, 0);
for(var i = 0; i < 3; i++) {
console.log(gfg());
}
输出:
[ 5, ‘Length of Geeks is 5’ ]
[ 3, ‘Length of for is 3’ ]
[ 5, ‘Length of Geeks is 5’ ]
示例 2:
// Defining underscore contrib variable
var _ = require('underscore-contrib');
var iter = _.iterators.List(["A", "ABA", "ABCBA", "ABA", "A"]);
function calculateLength(geeky, element) {
return [element.length, 'Length of '+element+'is '+element.length];
}
var gfg = _.iterators.accumulate(iter, calculateLength, 0);
for(var i = 0; i < 5; i++) {
console.log(gfg());
}
输出:
[ 1, ‘Length of A is 1’ ]
[ 3, ‘Length of ABA is 3’ ]
[ 5, ‘Length of ABCBA is 5’ ]
[ 3, ‘Length of ABA is 3’ ]
[ 1, ‘Length of A is 1’ ]