在JavaScript中将数组迭代为一对(当前,下一个) [英] Iterate an array as a pair (current, next) in JavaScript
问题描述
在问题将列表迭代为对(当前,在Python 中,OP有兴趣将Python列表迭代为一系列当前,下一个
对。我有同样的问题,但我想尽可能以最干净的方式在JavaScript中完成,也许使用 lodash 。
In the question Iterate a list as pair (current, next) in Python, the OP is interested in iterating a Python list as a series of current, next
pairs. I have the same problem, but I'd like to do it in JavaScript in the cleanest way possible, perhaps using lodash.
使用简单的 for
循环很容易做到这一点,但它感觉不是很优雅。
It is easy to do this with a simple for
loop, but it doesn't feel very elegant.
for (var i = 0; i < arr.length - 1; i++) {
var currentElement = arr[i];
var nextElement = arr[i + 1];
}
Lodash几乎可以做到这一点:
Lodash almost can do this:
_.forEach(_.zip(arr, _.rest(arr)), function(tuple) {
var currentElement = tuple[0];
var nextElement = tuple[1];
})
微妙的问题这在最后一次迭代中, nextElement
将是 undefined
。
The subtle problem with this that on the last iteration, nextElement
will be undefined
.
当然,理想的解决方案只是成对
lodash函数,只在必要时循环。
Of course the ideal solution would simply be a pairwise
lodash function that only looped as far as necessary.
_.pairwise(arr, function(current, next) {
// do stuff
});
是否有任何现有的库已经执行此操作?或者还有另一种在JavaScript中进行成对迭代的好方法我还没有尝试过?
Are there any existing libraries that do this already? Or is there another nice way to do pairwise iteration in JavaScript that I haven't tried?
澄清:如果 arr = [1,2,3,4]
,然后我的成对
函数将迭代如下: [1,2]
, [2,3]
, [3,4]
,不是 [1,2]
, [3,4]
。这是OP在 Python的原始问题中所要求的内容。
Clarification: If arr = [1, 2, 3, 4]
, then my pairwise
function would iterate as follows: [1, 2]
, [2, 3]
, [3, 4]
, not [1, 2]
, [3, 4]
. This is what the OP was asking about in the original question for Python.
推荐答案
不确定为什么要这样,但你可以在功能上做出丑陋的部分那看起来不错:
Not sure why you want this but you can just make the "ugly" part on a function and then it looks nice:
arr = [1, 2, 3, 4];
function pairwise(arr, func){
for(var i=0; i < arr.length - 1; i++){
func(arr[i], arr[i + 1])
}
}
pairwise(arr, function(current, next){
console.log(current, next)
})
您甚至可以稍微修改它以便能够迭代所有i,i + n对,而不仅仅是下一个:
You can even slightly modify it to be able to make iterate all i, i+n pairs, not just the next one:
function pairwise(arr, func, skips){
skips = skips || 1;
for(var i=0; i < arr.length - skips; i++){
func(arr[i], arr[i + skips])
}
}
pairwise([1, 2, 3, 4, 5, 6, 7], function(current,next){
console.log(current, next) // displays (1, 3), (2, 4), (3, 5) , (4, 6), (5, 7)
}, 2)
这篇关于在JavaScript中将数组迭代为一对(当前,下一个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!