本文整理了一些在日常工作可以用到的JavaScript数组小技巧
去重
巧用Set特性
1 2 3 4
| const arr = [1, 2, 2, 3, 4, 7, 7] const uniqueArr = [...new Set(arr)] console.log(uniqueArr)
|
某一个位置插入元素
改变原数组
1 2 3 4
| const arr = [1, 2, 3, 5, 6, 7] arr.splice(3, 0, 4) console.log(arr)
|
不改变原数组
1 2 3 4 5 6 7 8
| const arr = [1, 2, 4, 5] const indexNeededToInsert = 2 const newArr = [...arr.slice(0, indexNeededToInsert), 3, ...arr.slice(indexNeededToInsert)]
console.log(newArr)
console.log(arr)
|
删除某一个位置的元素
不改变原数组
1 2 3 4 5 6 7
| const arr = [1, 2, 3, 4, 5] const indexToBeRemoved = 3 const filteredArr = arr.filter((_, index) => index !== indexToBeRemoved) console.log(filteredArr)
console.log(arr)
|
改变原数组
1 2 3 4 5
| const arr = [1, 2, 3, 4, 5] const indexToBeRemoved = 3 arr.splice(indexToBeRemoved, 1) console.log(arr)
|
获取数组最后一个元素
改变原数组
1 2 3 4 5 6
| const arr = [1, 2, 3, 4, 5] const lastElement = arr.pop() console.log(lastElement)
console.log(arr)
|
不改变原数组
1 2 3 4 5 6
| const arr = [1, 2, 3, 4, 5] const lastElement = arr.slice(-1)[0] console.log(lastElement)
console.log(arr)
|
slice第一个参数如果是负数表示从后面开始数起的第几个元素,-1表示倒数第一个元素。
清空数组
1 2 3 4 5 6
| const arr = [1, 2, 3, 4, 5] arr.length = 0 console.log(arr)
console.log(arr[0])
|
生成一定长度的数组
1 2 3
| const newArr = new Array(10) console.log(newArr)
|
两个数组的交集
1 2 3 4 5
| const arr1 = [1, 2, 3, 4] const arr2 = [2, 3] const intersectedArr = arr1.filter(item1 => arr2.includes(item1)) console.log(intersectedArr)
|
合并多个数组
1 2 3 4 5 6
| const arr1 = [1, 2, 3] const arr2 = [4, 5, 6] const arr3 = [7, 8, 9] const mergedArr = [...arr1, ...arr2, ...arr3] console.log(mergedArr)
|
移除数组的虚假(falsy)值
1 2 3 4
| const mixedArr = [0, “blue”, “”, NaN, 9, true, undefined, “white”, false] const trueArr = mixedArr.filter(Boolean); console.log(trueArr)
|
求和
1 2 3 4
| const nums = [1, 2, 3, 4, 5] const sum = nums.reduce((currSum, num) => currSum + num) console.log(sum)
|
个人技术动态
欢迎关注公众号进击的大葱一起学习成长