数组位置移动

// 交换数组元素
var swapItems = function (arr, index1, index2) {
   arr[index1] = arr.splice(index2, 1, arr[index1])[0];
   return arr;
};

// 上移
var upRecord = function (arr, $index) {
   if ($index == 0) {
      return;
   }
   swapItems(arr, $index, $index - 1);
};

// 下移
var downRecord = function (arr, $index) {
   if ($index == arr.length - 1) {
      return;
   }
   swapItems(arr, $index, $index + 1);
};
// 上下多位置移动
var change = function (arr, to, from) {
   if (to < from) {
      for (let i = to; i < from; i++) {
         downRecord(arr, i);
      }
   }
   if (to > from) {
      for (let i = to; i > from; i--) {
         upRecord(arr, i);
      }
   }
   return arr;
};
posted @ 2022-02-15 14:29  nate_pan  阅读(154)  评论(0)    收藏  举报