數組元素的上移、下移


有時候我們需要數組元素進行移動,交換位置。我們可以使用一行代碼實現。

//要移動的數組
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM