ES6知识之数组

扩展运算符

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)
  1. target(必需):从该位置开始替换数据。如果为负值,表示倒数。
  2. start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。
  3. 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) // '辉'
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值