有時候我們需要數組元素進行移動,交換位置。我們可以使用一行代碼實現。
//要移動的數組 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