封装方法
// 上移操作
export function moveUp(array, index) {
if (index > 0 && index < array.length) {
let temp = array[index];
array[index] = array[index - 1];
array[index - 1] = temp;
}
return array;
}
// 下移操作
export function moveDown(array, index) {
if (index >= 0 && index < array.length - 1) {
let temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
return array;
}
// 置顶操作
export function moveToTop(array, index) {
if (index > 0 && index < array.length) {
let element = array.splice(index, 1)[0];
array.unshift(element);
}
return array;
}
// 置底操作
export function moveToBottom(array, index) {
if (index >= 0 && index < array.length - 1) {
let element = array.splice(index, 1)[0];
array.push(element);
}
return array;
}
// 将数组按数量分成子数组 如[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] ---结果 [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11 ] ]
export function arrayGrouping(array, chunkSize) {
let result = [];
for (let i = 0; i < array.length; i += chunkSize) {
result.push(array.slice(i, i + chunkSize));
}
return result;
}
使用的时候,先导入要使用的方法,再将原数据深拷贝一份,再操作如
let list = [{lable:'1',value:1},{lable:'2',value:2},{lable:'3',value:3},lable:'4',value:4}]
const copyArr = JSON.parse(JSON.stringify(list))
list = moveToTop(copyArr, index) // index:当前操作项的下标