扩展运算符
ES6通过扩展运算符...
,将一个数组转为用逗号分隔的参数序列。
console.log(...[1, 2, 3]) // 1 2 3
console.log('a', ...[1, 2, 3], 'b') // a 1 2 3 b
函数调用的时候,将一个数组变为参数序列
let array = [1, 2, 3]
function push(array,...items) {
array.push(...items)
}
push(array,...[4, 5, 6])
console.log(array) // [1, 2, 3, 4, 5, 6]
替换函数的apply()方法
// ES5
function f(x, y, z) {
}
const args = ['渣', '渣', '辉']
f.apply(null, args)
// ES6
function f(x, y, z) {
}
const args = ['渣', '渣', '辉']
f(...args)
扩展运算符的应用
数组复制
let a1 = ['渣','渣', '辉']
let [...a2] = a1
console.log(a2) // ['渣', '渣', '辉']
数组合并
let b1 = ['渣','渣']
let b2 = ['辉','啊']
let b3 = [...b1,...b2]
console.log(b3) // ['渣', '渣', '辉', '啊']
字符串转数组
[...'渣渣辉'] // ['渣', '渣', '辉']
新增方法
Array.from()
将类似数组
的对象和可遍历
的对象转为真正的数组
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
}
let arr = Array.from(arrayLike)
console.log(arr) // ['a', 'b', 'c']
Array.of()
将一组值转为数组
let arr = Array.of(1,2,3)
console.log(arr) // [1, 2, 3]
copyWithin()
在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组
Array.prototype.copyWithin(target,start,end)
- target(必需):从该位置开始替换数据。如果为负值,表示倒数。
- start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。
- end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。
const arr = ['渣','渣','辉']
console.log(arr.copyWithin(0, 2)) // ['辉', '渣', '辉']
find()、findIndex()
find()
用于找出第一个符合条件的数组成员
let arr = [1, 2, 3, 4]
let arr2 = arr.find((item,index,arr)=>{
return item > 1
})
console.log(arr2) // 2
findIndex()
返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回 -1
let arr = [1, 2, 3, 4]
let arr2 = arr.findIndex((item,index,arr)=>{
return item > 1
})
console.log(arr2) // 1
fill()
使用给定值,填充一个数组
let arr = [1, 2, 3].fill('渣')
console.log(arr) // ['渣', '渣', '渣']
keys()、values()、entries()
keys()
是对键名的遍历
values()
是对键值的遍历
entries()
是对键值对的遍历
for(let index of ['渣', '渣', '辉'].keys()){
console.log(index)
}
// 0
// 1
// 2
for(let item of ['渣', '渣', '辉'].values()){
console.log(item)
}
// 渣
// 渣
// 辉
for(let [index, item] of ['渣', '渣', '辉'].entries()){
console.log(index,item)
}
// 0 '渣'
// 1 '渣'
// 2 '辉'
includes()
用户判断数组是否包含给定的值
['渣', '渣', '辉'].includes('渣') // true
['渣', '渣', '辉'].includes('啊') // false
at()
接受一个整数作为参数,返回对应位置的成员,并支持负索引
const arr = ['渣', '渣', '辉']
arr.at(1) // '渣'
arr.at(-1) // '辉'