本文主要记录es6中对数组的拓展和一些常用的拓展方法
扩展运算符
- 形式:...[1,2,3] --- 三个点跟一个数组
- 作用:将一个数组转换成参数序列
- 用途:可以用在任何地方,通常和方法的调用连用
console.log(...[1,2,3]) //1 2 3
console.log(1,...[2,3,4],5) //1 2 3 4 5
function add(x,y) {
console.log(x+y)
}
add(...[7,8]) //15
和函数拓展中的rest参数对比
- 可以理解为数组的扩展运算符和函数的rest参数在作用上互逆的
- rest参数,是将不固定个数的参数作为数组,传入到函数中
- 扩展运算符,将数组元素拆分成单个元素的参数序列
function push(array,...items) {
array.push(...items)
console.log(array) //[1,2,3,4,5]
}
let arrTmp = []
push(arrTmp,1,2,3,4,5)
-
扩展运算符的更多用途:
- 数组合并
let arr1 = [1,2,3] let arr2 = [4,5] console.log(arr1.concat(arr2)) //[1,2,3,4,5] console.log([...arr1,...arr2]) //[1,2,3,4,5]
- 解构赋值
和解构赋值连用的时候,需要将其放在参数最后一个,否则会报错
const [first,...rest] = [1,2,3,4,5] console.log(first) //1 console.log(rest) //[2,3,4,5]
- 将字符串转换为数组
console.log([...'es6']) //["e", "s", "6"]
Array.of()
将一组值转换为数组
console.log(Array.of(1,2,3)) //[1, 2, 3]
copyWithin()
在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组
Array.prototype.copyWithin(target, start = 0, end = this.length)
- target(必需):从该位置开始替换数据。如果为负值,表示倒数。
- start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数
- end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
[1, 2, 3, 4, 5].copyWithin(0, 3) //[4, 5, 3, 4, 5] -- 用下标为3到结束位置的数组项从第一位开始替换
[1, 2, 3, 4, 5].copyWithin(0, 3, 4) // [4, 2, 3, 4, 5]
// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1) // [4, 2, 3, 4, 5]
find()
- 用于找出第一个符合条件的数组成员。
- 它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。
- 如果没有符合条件的成员,则返回undefined
[1, 5, 10, 15].find(function(value, index, arr) {
return value > 9;
})
findIndex()
- 返回第一个符合条件的数组成员的位置
- 如果所有成员都不符合条件,则返回-1。
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
}) // 2
includes()
表示某个数组是否包含给定的值
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true