1. 程式人生 > >js實現上移和下移

js實現上移和下移

class Utils {
    swapArray(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },

    // 上移 將當前陣列index索引與後面一個元素互換位置,向陣列後面移動一位
    moveUp(arr, index) {
      this.swapArray(arr, index, index - 1);
    },

    // 下移 將當前陣列index索引與前面一個元素互換位置,向陣列前面移動一位
    moveDown(arr, index) {
      this.swapArray(arr, index, index + 1);
    },
}