当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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’ ]




相关用法


注:本文由纯净天空筛选整理自Jitender_1998大神的英文原创作品 Underscore.js _.iterators.accumulateWithReturn() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。