es6学习之数组的扩展

一.扩展运算符

类似于rest的反向操作,将一个数组变为用都好分割的参数序列,展开数组

console.log(...[1, 2, 3])
// 1 2 3

应用1:深度复制数组

let arr = [1,2,3,4];
let arr2 = [...arr];
arr.copyWithin(1,2,3);  
arr     // 1,3,3,4
arr2    // 1,2,3,4

应用2:合并数组

// ES5
[1, 2].concat(more)
// ES6
[1, 2, ...more]

应用3:和解构赋值结合,需在最后一个位置

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   // []

4.字符串

[...'hello'];   //'h','e','l','l','o'

5.任何实现了Iterator接口的对象都能都可以使用扩展运算符

let nodeList = document.querySelectorAll('div');
let array = [...nodeList];

二.Array的方法

1.Array.from(arrayLike,fn) ,fn可以对arrayLike中每一项做操作

将类似于数组的对象(具有length属性)和具有可遍历的对象(Set和Map)转化为真正的数组

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

let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

2.Array.of(),将一组值转化为数组

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

3.copyWithin(),

Array.prototype.copyWithin(target, start = 0, end = this.length)

// 选取start-end范围内的数值,从target开始替换,有多少替换多少
[1, 2, 3, 4, 5 , 6,7,8,9,10].copyWithin(0, 2,5);
// [3, 4, 5, 4, 5, 6, 7, 8, 9, 10]

4.数组实例的 find() 和 findIndex()

find()方法找到数组中第一个符合条件的值,并返回值
findIndex()方法返回第一个符合条件的值的下标

5.数组实例的 fill()

填充一个数组

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

6.数组实例的 entries(),keys() 和 values()

目前chrome不支持

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"

7.数组实例的 includes()

返回boolean,判断数组包含某一个值

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

三.Array的空位处理

空位不是undefined,array空位处理严重不一致,所以尽量避免出现空位

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值