用数组建立一个简单的循环
有时我们需要不停的循环数组的元素,就像一组旋转的图片,或者音乐的播放列表。这里告诉你如何使一个数组拥有循环的能力:
function makeLooper(arr) {
  arr.loopIdx = 0;
  arr.current = function() {
    this.loopIdx = ( this.loopIdx ) % this.length;
    return arr[this.loopIdx]
  }
  arr.next = function() {
    this.loopIdx++;
    return this.current(); 
  }
  arr.prev = function() {
    this.loopIdx--;
    return this.current()
  }
}
var aList = ['A','B','C','D','E']
makeLooper(aList)
console.log(aList.current())  // A
console.log(aList.next())     // B
console.log(aList.next())     // C
console.log(aList.prev())     // B

发表评论 (审核通过后显示评论):