array 数组操作方法
ts
/**
* 删除某个元素,比较引用地址
*/
export function removeItem<T = any>(array: T[], item: T) {
const index = array.indexOf(item)
if (index === -1) {
console.warn(`数组中不包含${item}`)
return
}
array.splice(index, 1)
}
/**
* 删除某个元素,比较json格式化的值
*/
export function removeItemByJson<T = any>(array: T[], item: T) {
const jsonStr = JSON.stringify(item)
for (let index = 0; index < array.length; index++) {
const itemStr = JSON.stringify(array[index])
if (itemStr === jsonStr) {
array.splice(index, 1)
return
}
}
console.warn(`数组中不包含${item}`)
}
/**
* 下标位置向前移动一位
*/
export function moveForward(array: any[], index: number) {
if (index > 0 && index < array.length) {
// eslint-disable-next-line prefer-destructuring, no-param-reassign
array[index] = array.splice(index - 1, 1, array[index])[0]
}
}
/**
* 下标位置向后移动一位
*/
export function moveBack(array: any[], index: number) {
if (index >= 0 && index < array.length - 1) {
// eslint-disable-next-line prefer-destructuring, no-param-reassign
array[index] = array.splice(index + 1, 1, array[index])[0]
}
}
/**
* 下标处作为第一项,然后重新排序
*/
export function moveFirstAndReOrder(array: any[], index: number) {
const len = array.length - 1
if (index >= 0 && index <= len) {
;[...array].forEach((item, i, list) => {
if (i >= index) {
// eslint-disable-next-line no-param-reassign
array[i - index] = item
} else {
// eslint-disable-next-line no-param-reassign
array[array.length - 1 - i] = list[index - 1 - i]
}
})
}
}