主题
array-move
介绍
array-move 是一个用于在数组中移动元素的函数。它可以将数组中的一个元素从一个位置移动到另一个位置。
安装
bash
npm i array-move使用
js
import { arrayMoveImmutable } from 'array-move'
const input = ['a', 'b', 'c']
const array1 = arrayMoveImmutable(input, 1, 2)
console.log(array1)
//=> ['a', 'c', 'b']
const array2 = arrayMoveImmutable(input, -1, 0)
console.log(array2)
//=> ['c', 'a', 'b']
const array3 = arrayMoveImmutable(input, -2, -3)
console.log(array3)
//=> ['b', 'a', 'c']API
arrayMoveImmutable(array, fromIndex, toIndex)
克隆给定的数组,将指定元素移动到新位置,并返回新的数组。原数组不会被修改。
| 参数 | 类型 | 说明 |
|---|---|---|
| array | Array | 要操作的数组 |
| fromIndex | number | 要移动的元素索引(可为负数) |
| toIndex | number | 要移动到的位置索引(可为负数) |
fromIndex 和 toIndex 如果为负数,则从数组末尾倒数计算。
arrayMoveMutable(array, fromIndex, toIndex)
将指定元素在原数组中移动到新位置。适用于超大数组,对性能有极高要求时使用。
| 参数 | 类型 | 说明 |
|---|---|---|
| array | Array | 要操作的数组 |
| fromIndex | number | 要移动的元素索引(可为负数) |
| toIndex | number | 要移动到的位置索引(可为负数) |
fromIndex 和 toIndex 如果为负数,则从数组末尾倒数计算。
