ES6 数组的扩展

107 阅读7分钟

扩展运算符

扩展运算符...将一个数组转为用逗号分隔的参数序列。

console.log(...[1, 2, 3]) // 1 2 3
[...document.querySelectorAll('div')]
// [<div>,<div>,<div>]

只有在函数调用时,扩展运算符才可以放在圆括号中,否则会报错。
下面是扩展运算符取代apply()的例子。

Math.max.apply(null, [14, 3, 77])
// 等同于
Math.max...[14, 3, 77])
// 等同于
Math.max(14, 3, 77)

扩展运算符的应用

  1. 复制数组
const a1 = [1, 2]
const a2 = [...a1]
const [...a2] = a1
  1. 合并数组
const a1 = [0, 1, 2]
const a2 = [3, 4, 5]
const a3 = [6, 7, 8]

// ES5的写法
a1.concat(a2, a3) // [0, 1, 2, 3, 4, 5, 6, 7, 8]

// ES6的写法
[...a1, ...a2, ...a3]
  1. 与解构赋值结合用于生成数组,若扩展运算符用于数组赋值,只能放在尾参。
const [first, ...rest] = [1,2,3,4,5]
first // 1
rest // [2,3,4,5]

const [first, ...rest] = []
first // undefined
rest // []

const [first, ...rest] = ['foo']
first // 'foo'
rest // []
  1. 扩展运算符可以将字符串转为真正的数组
[...'hello']
// ['h', 'e', 'l', 'l', 'o']
  1. 只要具有Iterator接口的对象都可以使用扩展运算符。

Array.from()

Array.from()可以将类似数组的对象和可遍历的对象转为真正的数组。

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
}

let a2 = Array.from(arrayLike) // ['a', 'b', 'c']

只要部署了Iterator接口的数据结构,Array.from()都可以将其转为数组。

Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

如果参数是一个真正的数组,Array.from()会返回一个相同的数组。
所谓类似数组的对象,必须有length属性。任何有length属性的对象都能通过Array.from()转为数组。

Array.from({ length: 3 })
// [undefined, undefined, undefined]

Array.from()接受一个函数为第二个参数,用来对每个元素进行处理,将处理后的值放入返回的数组。

Array.from([1, 2, 3], x => x * x)
// [1, 4, 9]

Array.from()的第三个参数用来绑定thisArray.from()可以将各种值转为真正的数组,并且还提供map功能。

Array.from({ length: 2 }, () => 'jack')

Array.from()也可以将字符串转为数组,然后返回字符串的长度。

function countSymbols(string) {
    return Array.from(string).length
}

Array.of()

Array.of()用于将一组值转换为数组。

Array.of(3) // [3]
Array.of(1, 3, 8) // [1, 3, 8]

这个方法用于弥补构造函数Array()的不足,由于参数个数不同,会导致Array()的行为有差异。

Array() // []
Array(3) // [, , ,]
Array(1, 3, 8) // [1, 3, 8]

只有当参数个数不少于2个时,Array()才会返回由参数组成的新数组,参数只有一个正整数时,实际在指定数组的长度。

实例方法:copyWithin()

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号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

// 等同于
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]

// 将2号位到数组结束,复制到0号位
let arr = new Inet32Array([1, 2, 3, 4, 5])
arr.copyWithin(0, 2)
// [3, 4, 5, 4, 5]

// 没有部署copyWithin的平台需要用下面的写法
[].copyWithin.call(new Int32Array[1, 2, 3, 4, 5], 0, 3, 4)

实例方法:find(),findIndex(), findLast(),findLastIndex()

find()方法用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找到第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined

[1, 4,-5, 10].find(n => n < 0)
// -5

find()方法的回调函数可以接受三个参数,依次为当前的值,当前的位置和原数组。

[1, 5, 6, 13].find((value, index, arr) => {
    return value > 9
})
// 13

findIndex()方法返回第一个符合条件的数组成员的位置,如果找不到则返回-1

[1, 5, 6, 13].findIndex((value, index, arr) => {
    return value > 9
})
// 3`

这两个方法都可以接受第二个参数,用来绑定回调函数的this对象。

function compareAge(v) {
    return v > this.age
}
let person = {name: 'xx', age: 20}
[17, 20, 23, 14].find(f, person) // 23

findLast()findLastIndex()从数组最后一个成员开始,找出第一个符合条件的成员。

const arr = [
    {value:1},
    {value:2},
    {value:3},
    {value:4}
]
arr.findLast(n => n.value===3) // {value:3}
arr.findLastIndex(n => n.value===3) // 2

实例方法:fill()

fill()方法使用给定值,填充一个数组。它可以接收第二个和第三个参数,用于指定填充的起始位置和结束位置。

['a', 'b', 'c'].fill(7)
// [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]

['a', 'b', 'c'].fill(7,1,2)
['a', 7, 'c']

如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝(即原对象的值也会发生改变)。

let obj = {name: "Mike"}
let arr = new Array(3).fill(obj);
arr[0].name = "Ben";

obj // {name: "Ben"}
arr // [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]

实例方法:entries(),keys(),values()

entries()keys()values()用于遍历数组,他们都返回 一个遍历器对象,可以用for...of遍历。

// 对键名遍历
for(let i of ['a','b'].keys()){
    console.log(i)
}
// 0
// 1

// 对键值遍历
for(let el of ['a','b'].values()){
    console.log(el)
}
// 'a'
// 'b'

// 对键值对遍历
for(let [i,el] of ['a','b'].entries()){
    console.log(i,el)
}
// 0 'a'
// 1 'b'

也可以用next()方法对遍历器对象进行遍历。

['a','b'].entries().next().value // [0, 'a']

实例方法:includes()

includes()方法返回一个布尔值,表示某个数组是否包含给定的值。

[1,2,3].includes(2) // true
[1,2,NaN].includes(NaN) // true

该方法第二个参数表示搜索的起始位置,默认为0.如果为负数,表示倒数的位置,当超出数组长度,则会重置为0.

[1,2,3].includes(3,1) // true
[1,2,3].includes(3,3) // false
[1,2,3].includes(3,-4) // true

实例方法:flat(),flatMap()

flat()方法用于将嵌套的数组变成一维数组。该方法返回一个新数组,不改变原数组。

[1,2,[3,4]]flat()
// [1,2,3,4]

flat()方法默认只会“拉平”一层,它接受整数参数,表示想要拉平的层数,默认为1。

[1,2,[3,4,[5]]].flat(2)
// [1,2,3,4,5]

[1,2,[3,4,[5]]].flat()
// [1,2,3,4,[5]]

如果不管有多少层嵌套,都要转成一维数组,可以用Infinity作为参数。

[1,2,[3,4,[5]]].flat(Infinity)
// [1,2,3,4,5]

如果原数组有空位,flat()方法会跳过空位。

[1,2, ,3,4].flat()
// [1,2,3,4]

flatMap()方法对原数组的每个成员执行一个函数,然后对返回值组成的数组执行flat()方法。该方法不改变原数组。

[1,2,3].flatMap(x=>[x,x*2])
// [1,2,2,4,3,6]

// flatMap()只能展开一层数组
[1,2,3].flatMap(x=>[[x]])
[[1],[2],[3]]

flatMap()方法的参数函数可以接受三个参数,分别是当前数组成员当前位置、原数组。

实例方法:at()

at()方法接受一个整数作为参数,返回对应位置成员,并支持负索引。如果参数位置超过数组范围,则返回undefined

const arr=[4,12,5,13,22]
arr.at(-1) // 22
arr.at(3) // 13

实例方法:toReversed(),toSorted(),toSpliced(),with(index,value)

这四种方法分别对应reverse()sort()splice()splice(index,1,value),含义和用法完全一样,但不会改变原数组。

实例方法:group(),groupToMap()

group()方法接受一个函数为参数,原数组的每个成员会依次执行这个函数,确定自己属于哪一组。这个函数接受三个参数,分别是当前数组成员、当前位置和原数组,它的返回值为字符串,作为分组后的组名。

const arr=[1,2,3,4,5]
arr.group((num,index,array)=>{
    return num%2===0?'even':'odd'
})
// {odd:[1,3,5],even:[2,4]}

group()的返回值是一个对象,该对象的键名就是每一组的组名,该对象的键值是一个数组,包括所有产生当前键名的原数组成员。group()还可以接受一个对象为第二参数,该对象会绑定第一个参数里的this
groupToMap()用法与group()一致,但它返回值是一个Map结构。

const array=[1,2,3,4,5]
const odd={odd:true}
const even={even:true}
array.groupToMap(x=>{
    return x%2===0? even: odd
})
// Map{{odd :true}:[1,3,5],{even:true}:[2,4]}

数组的空位

ES6明确将空位转为undefined

Array.from(['a',,'b']) // ['a',undefined,'b']
[...['a','b']] // ['a',undefined,'b']