在两个方向上迭代一个范围
Iterating through a 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
检查。
如果没有if,有什么办法可以解决吗?也许是单线的?
要将两个 if
变成一个无条件语句,您可以将 range.length
添加到 currentIndex
,然后使用模数:
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));
有一个非常常见和简单的任务,即在两个方向上通过某个范围进行循环迭代:
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
检查。
如果没有if,有什么办法可以解决吗?也许是单线的?
要将两个 if
变成一个无条件语句,您可以将 range.length
添加到 currentIndex
,然后使用模数:
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));