双向迭代范围 [英] Iterating through a range in both directions

查看:112
本文介绍了双向迭代范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在两个方向的某个范围内进行循环迭代是一项非常常见且简单的任务:

There is a very common and easy task of looped iteration through some range in both directions:

var currentIndex = 0;
var range = ['a', 'b', 'c', 'd', 'e', 'f'];

function getNextItem(direction) {
    currentIndex += direction;
    if (currentIndex >= range.length) { currentIndex = 0; }
    if (currentIndex < 0) { currentIndex = range.length-1; }

    return range[currentIndex];
}        
// get next "right" item
console.log(getNextItem(1));

// get next "left" item
console.log(getNextItem(-1));

上面的代码运行完美,但是我花了大约一个小时试图摆脱两次if检查.

The code above works perfectly, but I spent about an hour trying to get rid of double if check.

有没有办法解决如果没有的话?可能是单线的?

Is there any way to solve if without if? Sort of one-liner maybe?

推荐答案

要将两个if变成一个无条件语句,可以将range.length添加到currentIndex,然后使用取模:

To turn the two ifs into one unconditional statement, you can add the range.length to the currentIndex and then use modulo:

var currentIndex = 0;
var range = ['a','b','c','d','e','f'];

function getNextItem(direction) {
    currentIndex = (currentIndex + direction + range.length) % range.length;
    return range[currentIndex];
}

// get next "right" item
console.log(getNextItem(1));
console.log(getNextItem(1));

// get next "left" item
console.log(getNextItem(-1));
console.log(getNextItem(-1));
console.log(getNextItem(-1));

console.log(getNextItem(4));
console.log(getNextItem(1));
console.log(getNextItem(1));
console.log(getNextItem(1));

这篇关于双向迭代范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆