array.js
483 Bytes
/**
* @param {Array} arr 原数组
* @param {number} fromIndex 原下标
* @param {number} toIndex 目标下标
* @returns {Array} 新数组,不修改原数组
*/
export function moveItem(arr, fromIndex, toIndex) {
if (fromIndex === toIndex)
return [...arr];
// 先拷贝一份新数组
const newArr = [...arr];
// 取出并删除原位置元素
const item = newArr.splice(fromIndex, 1)[0];
// 插入到目标位置
newArr.splice(toIndex, 0, item);
return newArr;
}