ES6之数组的扩展(ES6对于数组的新增方法)

扩展运算符(...)

扩展运算符(spread)是三个点(...),他如同rest参数的逆运算,将一个数组转为逗号分隔的参数序列

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

该运算主要用于函数调用

function push(array. ...items){
    array.push(...items);
}

应用:

合并数组

[1, 2].concat(more);    <==>     arr1.concat(arr2, arr3);

[1, 2, ...more]  <==>      [...arr1, ...arr2, ...arr3];

与解构赋值结合

a = list[0],rest = list.slice(1);
[a, ...rest] = list;

如果将扩展运算符用于数组赋值,则只能将其放在参数的最后一位。

const [first, ...rest] = [1, 2, 3, 4, 5]

//first = 1

//rest = [2, 3, 4, 5]

函数的返回值

字符串

[...’hello’]

// [“h”, “e”, “l”, “l”, “o”]

实现iterator接口对象

Map和Set解构、Generator函数

扫描二维码关注公众号,回复: 4109062 查看本文章

Array.from()

将两类对象转为指正的数组:类似数组的对象(array-like object)和可遍历(iterable)对象

let arrayLike = {

‘0’: ‘a’,

‘1’: ‘b’,

‘2’: ‘c’,

}

Let arr1 = Array.from(arrayLike);   //[‘a’, ‘b’, ‘c’];

Array.from(‘hello’)    // [“h”, “e”, “l”, “l”, “o”]

Array.from可接受第二个参数,类似于数组的map方法,用来对每个元素进行处理

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

返回各种数据的类型

Array.from(arguments, value => typeof value)

Array.from({length: 2 }, () => ‘jack’);   //[‘jack’,‘jack’]

Array.of()

用于将一组值转化为数组

原方法

Array()         // []

Array(3)        //[, , ,]

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

新方法

Array.of()         // []

Array.of(undefined)        //[undefined]

Array.of(1)    //[1]

Array.of(1, 2)    //[1, 2]

数组实例的copyWithin()

数组实例的copyWithin方法会在当前数组的内部将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。

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

·target(必选):从该位置开始替换数据

·start(可选):从该位置开始读取数据,如果为负值,表示倒数

·end(可选):从该位置停止读取数据,如果为负值,表示倒数

例子:

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

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

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

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

findIndex()法与find()类似,只是它返回的是成员的位置。

例子:

[1, 5, 15, 20].find((value, index, arr) => value > 9);    //15

[1, 5, 15, 20].findIndex((value, index, arr) => value > 9);    //2

数组实例的fill()

fill方法使用给定一个值填充一个数组

[‘a’, ‘b’, ‘c’].fill(7);     //[7, 7, 7]

[‘a’, ‘b’, ‘c’].fill(7, 1, 2);     //[‘a’, 7, ‘c’]

数组实例的entries()、kets()和values()

都用于遍历数组。Keys()是对键名遍历,values()是对键值的遍历,entries()是对键值对的遍历。

for( let index of [‘a’, ‘b’].keys() )

for( let elem of [‘a’, ‘b’].values() )

for( let [index , elem ] of [‘a’, ‘b’].entries() )

数组实例的includes()

返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似。

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

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

数组的空位

值数组的某一个位置没有任何值,空位不是指undefined,一个位置等于undefined依然是有值的。

注:·forEach()、filter()、every()和some()都会跳过空位

·map()会跳过空位,但会保留这个值

·join()和toString()会将空位视为undefined,而undefined和null会处理成空字符串

ES6明确将空位视为undefined

Array.from()会将空位转为Undefined

扩展运算符(...)也会将空位转为Undefined

copyWithin会将空位一起复制

fill()会将空位视为正常的数组位置

for...of循环也会遍历空位

猜你喜欢

转载自blog.csdn.net/DengZY926/article/details/83994052