用数组竖立一个简朴的轮回

偶然我们须要不断的轮回数组的元素,就像一组扭转的图片,或许音乐的播放列表。这里通知你怎样使一个数组具有轮回的才能:

var aList = ['A','B','C','D','E'];

function make_looper( arr ){

    arr.loop_idx = 0;

    // 返回当前的元素
    arr.current = function(){

      if( this.loop_idx < 0 ){// 第一次搜检
        this.loop_idx = this.length - 1;// 更新 loop_idx
      }

      if( this.loop_idx >= this.length ){// 第二次搜检
        this.loop_idx = 0;// 更新 loop_idx
      }

      return arr[ this.loop_idx ];//返回元素
    };
    
    // 增添 loop_idx 然后返回新的当前元素
    arr.next = function(){
      this.loop_idx++;
      return this.current();
    };
    // 削减 loop_idx 然后返回新的当前元素
    arr.prev = function(){
      this.loop_idx--;
      return this.current();
    };
}

make_looper( aList);

aList.current();// -> A
aList.next();// -> B
aList.next();// -> C
aList.next();// -> D
aList.next();// -> E
aList.next();// -> A
aList.pop() ;// -> E
aList.prev();// -> D
aList.prev();// -> C
aList.prev();// -> B
aList.prev();// -> A
aList.prev();// -> D

运用 % ( 取模 ) 操作符更文雅。取模返回除法的余数 ( 2 % 5 = 1 and 5 % 5 = 0):

var aList = ['A','B','C','D','E'];


function make_looper( arr ){

    arr.loop_idx = 0;

    // return current item
    arr.current = function(){
      this.loop_idx = ( this.loop_idx ) % this.length;// 无需搜检 !!
      return arr[ this.loop_idx ];
    };

    // 增添 loop_idx 然后返回新的当前元素
    arr.next = function(){
      this.loop_idx++;
      return this.current();
    };
    
    // 削减 loop_idx 然后返回新的当前元素
    arr.prev = function(){
      this.loop_idx += this.length - 1;
      return this.current();
    };
}

make_looper( aList);

aList.current();// -> A
aList.next();// -> B
aList.next();// -> C
aList.next();// -> D
aList.next();// -> E
aList.next();// -> A
aList.pop() ;// -> E
aList.prev();// -> D
aList.prev();// -> C
aList.prev();// -> B
aList.prev();// -> A
aList.prev();// -> D

转载自:http://www.jstips.co

    原文作者:大猛
    原文地址: https://segmentfault.com/a/1190000006228695
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞