【问题标题】:Using mod to wrap around使用 mod 环绕
【发布时间】:2019-04-15 00:31:16
【问题描述】:

假设数组的长度为 1000。我正在尝试创建一种简单的方法来遍历存储在数组中的图像路径而不会越界。下面的方法在单击“下一步”按钮以增加数组索引时使用模数很好地处理环绕,但当我必须从索引中减少和减去一个时(当用户单击上一个按钮时)。

基本上我想做的是:

998 -> click next -> 999
999 -> click next -> 0
0 -> click previous -> 999

我的 Javacript

var index = 0;

$('.catalog-img-container').attr("src", javascript_array[index]);
$(".next").click(function(){
        $('.catalog-img-container').attr("src", javascript_array[++index%arrayLength]);
    });         
$(".previous").click(function(){
    $('.catalog-img-container').attr("src", javascript_array[--index]);
    alert(index);

感谢任何帮助

非常感谢。

【问题讨论】:

  • --index%arrayLength 应该可以正常工作。
  • 试过了,不行。
  • @Shmiddty 应该,但没有。
  • 哦,我明白了,问题是索引小于0的时候。
  • 你试过 if/else 语句吗?

标签: javascript jquery


【解决方案1】:

可能有一个更优雅的方法来解决这个问题,但这很简单:

$(".previous").click(function(){
    if (--index < 0) index = arrayLength - 1;
    $('.catalog-img-container').attr("src", javascript_array[index%arrayLength]);
}); 

【讨论】:

    【解决方案2】:

    由于--index%arrayLength不起作用,只需在取模之前添加数组的长度即可:

    index = (index+arrayLength-1) % arrayLength
    

    你也可以

    (index+=arrayLength-1)%arrayLength
    

    但这会导致index 变得非常大,可能在足够长的时间内超出范围。

    【讨论】:

    • 索引小于-arrayLength时同样的问题
    • 已修复。看起来像一个两步问题。
    • 感谢您的回复。您在编辑之前的解决方案之一对我有用。但是,这不起作用。
    【解决方案3】:

    您也可以使用方便的对象。

    var Cursor = function (array) {
      var idx = 0;
      this.prev = function () {
        idx = (!!idx ? idx : array.length) - 1;
        return array[idx];
      };
      this.current = function () {
        return array[idx];
      };
      this.next = function () {
        idx = (idx + 1) % array.length;
        return array[idx];
      };
      return this;
    };
    

    例如,

    var $container = $(".catalog-img-container");
    var cursor = new Cursor(javascript_array);
    
    $container.attr("src", cursor.current());
    
    $(".next").click(function(){
      $container.attr("src", cursor.next());
    });         
    
    $(".previous").click(function(){
      $container.attr("src", cursor.prev());
    });
    

    【讨论】:

    • +1 表示方便的对象。我自己可能会以不同的方式写它,但这个概念很好。 :)
    • @Shmiddty,不知道这有什么帮助,但没关系。手感不错
    【解决方案4】:

    嗯,不确定这是不是你想要的,但是:

    $(".previous").click(function(){if (index-1 <0){index = arrayLength -1;}
    
                $('.catalog-img-container').attr("src", javascript_array[--index]);
                //alert(index);
            });  
    

    我假设 arrayLength = javascript_array.length;

    希望对你有帮助

    【讨论】:

      【解决方案5】:

      WORKING DEMO TEST

      这就是你所需要的:

      var index=0;
      
      $('.catalog-img-container').attr("src", javascript_array[index]);
      
      $(".next, .previous").click(function(){
      
        var MyClass = $(this).hasClass('next') ? index++ : index-- ;
        index = index==-1 ? arrayLength-1 : index%arrayLength ;  
        $('.catalog-img-container').attr("src", javascript_array[index]);
      
      }); 
      

      【讨论】:

      • index == index-1 永远不会是真的。
      • 感谢您的回复。这似乎是一个复杂的解决方案:)
      • @roXon 您编辑了您的答案,为什么还要费心将编辑与我的第一条评论(您的原始答案)进行比较?评论的重点是指出一个错误(可能是脑残,对吧?)不必为此感到难过。 :)
      • @Shmiddty 我不记得我的第一次编辑,我只知道我在其中添加了一个演示,但可能是我正在解决我的答案。不管怎么说,还是要谢谢你! :) 哈哈 脑残 :) 你让我开心!
      【解决方案6】:
      /**
      * @param {number} counter
      * @param {number} maxValue
      * @return {number}
      * @desc Always returns a number between 0 and maxValue. Can be used to 
      iterate through an array without "Range out of bounds" error.
      */
      export default function mapToRange(counter, maxValue) {
        if (maxValue === undefined || maxValue === 0) return 0;
        // positive counter
        if (counter >= 0) return counter % maxValue;
        // negative counter
        const modulo = counter % maxValue;
        if (modulo === 0) {
            return modulo;
        }
        return modulo + maxValue;
      }
      

      我使用这个函数将counter,一个int型数字映射到0到maxValue之间的范围内。

      let counter = 0;
      const array = ['apple', 'pear','peach'];
      if(press arrow up) counter--;
      else if (press arrow down) counter++;
      
      let idx = mapInRange(counter, array.length)
      console.log(array[idx]);
      

      假设您有一个下拉列表,并且您想使用箭头键在列表中导航。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-24
        • 2021-07-27
        • 2012-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多