背景
列表拖拽排序的时候有两种实现方案
- 旧位置和新位置交换数据
- 旧位置放到新位置,新位置和新位置之后的顺延(插队)
code
/**
* 1. 将 e => b,即 4 => 1
* a e b c d
*
* 2. 将 b => e,即 1 => 4
* a c d b e
*/
const arr = ['a', 'b', 'c', 'd', 'e']
function sss(oldIndex, newIndex) {
const arrCopy = [...arr]
const sliceIndex = oldIndex > newIndex ? newIndex : newIndex + 1
const spliceIndex = oldIndex > newIndex ? oldIndex + 1 : oldIndex
const newArr = [
...arrCopy.slice(0, sliceIndex),
arrCopy[oldIndex],
...arrCopy.slice(sliceIndex, arrCopy.length)
]
newArr.splice(spliceIndex, 1)
return newArr
}
console.log(sss(4, 1)) // ['a', 'e', 'b', 'c', 'd']
console.log(sss(1, 4)) // ['a', 'c', 'd', 'e', 'b']