数组解构赋值应用
// 交换变量
[a, b] = [b, a]
[o.a, o.b] = [o.b, o.a]
// 生成剩余数组
const [a, ...rest] = [...'asdf'] // a:'a',rest: ["s", "d", "f"]
数组浅拷贝
const arr = [1, 2, 3]
const arrClone = [...arr]
// 对象也可以这样浅拷贝
const obj = { a: 1 }
const objClone = { ...obj }
浅拷贝:拷贝的值改变时原来的值跟着一起改变。
深拷贝:拷贝的值可以无限层拷贝,拷贝值与原始值不发生任何影响
浅拷贝方法有很多如arr.slice(0, arr.length)/Arror.from(arr)
等,但是用了...
操作符之后就不会再想用其他的了~
数组合并
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const arr3 = [7, 8, 9]
const arr = [...arr1, ...arr2, ...arr3]
arr1.concat(arr2, arr3)
同样可以实现合并,但是用了...
操作符之后就不会再想用其他的了~
数组去重
const arr = [1, 1, 2, 2, 3, 4, 5, 5]
const newArr = [...new Set(arr)]
new Set(arr)
接受一个数组参数并生成一个set结构的数据类型。set数据类型的元素不会重复且是Array Iterator
,所以可以利用这个特性来去重。
数组取交集
const a = [0, 1, 2, 3, 4, 5]
const b = [3, 4, 5, 6, 7, 8]
const duplicatedValues = [...new Set(a)].filter(item => b.includes(item)) //includes判断数组里有无此value,返回布尔值
duplicatedValues // [3, 4, 5]
数组取差集
const a = [0, 1, 2, 3, 4, 5]
const b = [3, 4, 5, 6, 7, 8]
const diffValues = [...new Set([...a, ...b])].filter(item => !b.includes(item) || !a.includes(item)) // [0, 1, 2, 6, 7, 8]
数组转对象
const arr = [1, 2, 3, 4]
const newObj = {...arr} // {0: 1, 1: 2, 2: 3, 3: 4}
对象转数组
const obj = {a: '群主', b: '男群友', c: '女裙友', d: '未知性别'}
const flatArr = Object.values(obj); //["群主", "男群友", "女裙友", "未知性别"]
数组摊平
const obj = {a: '群主', b: '男群友', c: '女裙友', d: '未知性别'}
const getName = function (item) { return item.includes('群')}
// 方法1
const flatArr = Object.values(obj).flat().filter(item => getName(item))
// 经大佬指点,更加简化(发现自己的抽象能力真的差~)
const flatArr = Object.values(obj).flat().filter(getName)
复制代码
二维数组用array.flat()
,三维及以上用array.flatMap()
。
找到第一个符合条件的元素/下标
const arr = [1, 2, 3, 4, 5]
const findItem = arr.find(item => item === 3) // 返回子项
const findIndex = arr.findIndex(item => item === 3) // 返回子项的下标
// 我以后再也不想看见下面这样的代码了