正在获取下一个可用编号,跳过数组中的项目

Getting next available number, skipping items in an array

本文关键字:数组 项目 编号 获取 下一个      更新时间:2024-03-13

我得到了一个包含不可用插槽的数组。例如[4,6,7]如果我开始向上计数(索引++),一旦它达到3,下一个可用的插槽将是5。如果索引=5,则下一个可用插槽为8。

我找不到一个像样的方法来做那件事。我如何开发一个函数,返回下一个可用的插槽(给定向上或向下的计数方向)

var notAvailable = [4,6,7];
function nextSlot(current, direction) { ... }
nextSlot(2,'up');

如有任何帮助,我们将不胜感激。

您可以这样做。。。

var notAvailable = [4,6,7];
function nextSlot(current, direction) { 
   var inc = 1;
   if( direction == "down" ){
       inc = -1;
   }
   var next = current + inc;
   for(var i = 0; i < notAvailable.length; i++){
      if( notAvailable[i] == next ){
         return nextSlot(next , direction );
      }
   }
   return next ;
}
nextSlot(2,'up');

假设current为当前插槽:

var notAvailable = [4,6,7];
function nextSlot(current, direction) {
  var inc = direction === 'down' ? -1 : 1;
  var next = current;
  while(notAvailable.indexOf(next += inc) > -1);
  return next;
}
nextSlot(2, 'up'); // 3
nextSlot(3, 'up'); // 5
nextSlot(5, 'up'); // 8
nextSlot(5, 'down'); // 3
nextSlot(3); // 5 assumes no direction as 'up'

它使用了ES5中数组的indexOf方法。