数组元素的上移、下移

数组元素的上移、下移

有时候我们需要数组元素进行移动,交换位置。我们可以使用一行代码实现。

数组元素的上移、下移
//要移动的数组
let htmlArr = [
  {name: '赵一'},  
  {name: '钱二'},
  {name: '张三'},
  {name: '李四'}
];
数组元素的上移、下移

移动函数

数组元素的上移、下移
//排序函数(移动)
/*
上移 type 为 0, 下移为 1.
index 为 当前移动元素的下标
*/
function changeSort (index, type) {
  htmlArr.splice(type ? index : index - 1, 1, ...htmlArr.splice(type ? index + 1 : index, 1, htmlArr[type ? index : index - 1]));
};
数组元素的上移、下移

使用场景:

数组元素的上移、下移

demo 地址:https://codepen.io/namePeach/pen/mZGKKL?editors=1012