Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 80dc7bd

Browse files
committedApr 15, 2023
feat: 移动数组元素
1 parent 58aab91 commit 80dc7bd

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
 
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
let arr = [1, 2, 3, 4, 5]
2+
3+
function moveArray(arr, startIndex, endIndex) {
4+
let newArr = [...arr]
5+
switchItem(startIndex, newArr, endIndex)
6+
7+
return newArr
8+
}
9+
10+
function switchItem(startIndex, newArr, endIndex) {
11+
let _start = startIndex > 0 ? startIndex : newArr.length + startIndex
12+
if (_start >= 0 && _start < newArr.length) {
13+
let _end = endIndex > 0 ? endIndex : newArr.length + endIndex
14+
15+
const [item] = newArr.splice(startIndex, 1)
16+
newArr.splice(_end, 0, item)
17+
}
18+
}
19+
20+
console.log(moveArray(arr, 2, 3)) //[1,2,4,3,5]
21+
22+
// console.log(moveArray(arr, -1, -2)) //[1,2,3,5,4]

0 commit comments

Comments
 (0)
Please sign in to comment.