ES6之数组的扩展

本文详细介绍了ES6中的扩展运算符、数组的静态方法(from、of)、实例方法(copyWithin、find、findIndex、fill等)以及空位处理规则。涵盖了数组操作的基础知识和实用技巧,适合开发者深入理解并应用于实际项目中。
摘要由CSDN通过智能技术生成

1 扩展运算符

扩展运算符(spread)是三个点...,它的作用就好比 rest 参数的逆运算,即将一个数组转为参数序列

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

该运算符主要用于函数调用:

function add(x, y) {
  return x + y;
}
const numbers = [4, 38];
add(...numbers); // 42

再举个例子:求数组中的最大元素。显然利用扩展运算符可以替代apply方法。

// ES5 的写法
Math.max.apply(null, [14, 3, 77])

// ES6 的写法
Math.max(...[14, 3, 77])

再列举一些其他的应用场景:

//克隆数组
const a1 = [1, 2];
const a2 = [...a1];

//合并数组
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]

//与解构赋值结合使用:扩展运算符只能用于最后一个参数
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = [];
first // undefined
rest  // []
const [first, ...rest] = [666];
first  // 666
rest   // []

//分解字符串
[...'hello'] // ["h", "e", "l", "l", "o"]

2 数组的静态方法

2.1 from方法

Array.form方法用于将类似数组的对象可遍历对象(包括ES6中的MapSet)转为真正的数组

类似数组的对象(对象必须有length属性)如下所示:

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

利用from方法可以将其转为数组:

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

可遍历对象如下:

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

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

2.2 of方法

Array.of方法用于将一组值转为数组。该方法总是返回参数值组成的数组。如果没有参数,就返回一个空数组。

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

3 数组实例的方法

3.1 copyWithin方法

数组实例的copyWithin()方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。语法为:Array.prototype.copyWithin(target, start = 0, end = this.length)

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

3.2 find和findIndex方法

数组实例的find方法,用于找出第一个符合条件的数组成员。该方法的参数为一个回调函数。若都没有找到,则返回undefined

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

//等同于下面的写法:value为当前值,index为当前的位置,arr为原数组
[1, 4, -5, 10].find(function(value, index, arr) {
  return value < 1;
})

//等同于
[1, 4, -5, 10].find(function(value, index, arr) {
  return value < arr[0];
})

数组实例的findIndex方法则返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1

该方法与indexOf方法的区别如下:indexOf方法无法发现NaN,而findfindIndex方法弥补了这方面的不足。

[1,3,NaN].indexOf(NaN); // -1

[1,3,NaN].find(y => Object.is(NaN, y)) // NaN
[1,3,NaN].findIndex(y => Object.is(NaN, y)) //2

3.3 fill方法

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 arr = new Array(3).fill({name: "Mike"});
arr[0].name = "Ben";
arr // [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]

3.4 entries、keys和values方法

ES6 提供三个新的方法entries()keys()values()用于遍历数组,其中,keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

ES5的实现方法:

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

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

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

ES6的实现方法:

let letter = ['a', 'b', 'c'];
let keys = letter.keys();
let values = letter.values();
let entries = letter.entries();
for (let i=0; i<letter.length;i++){
	console.log(keys.next().value);
	console.log(values.next().value);
	console.log(entries.next().value);
}

ES2017 引入了跟Object.keys配套的Object.valuesObject.entries方法,作为遍历一个对象的补充手段,供for...of循环使用。

let {keys, values, entries} = Object;
let obj = { a: 1, b: 2, c: 3 };

for (let key of keys(obj)) {
  console.log(key); // 'a', 'b', 'c'
}

for (let value of values(obj)) {
  console.log(value); // 1, 2, 3
}

for (let [key, value] of entries(obj)) {
  console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
}

3.5 includes方法

Array.prototype.includes表示某个数组是否包含给定的值,与字符串的includes方法类似。还可以有第二个参数,表示搜索的起始位置(若为负数,表示倒数的位置,如-1表示倒数第一的位置)。举例如下:

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true ,这个和上面的find方法和findIndex方法类似
[1, 2, 3].includes(3, -1); //true
[1, 2, 3].includes(3, -1); //true,若负数超出范围,则从0开始
[1, 2, 3].includes(3, 5); //false,正数超出范围,则返回false

该方法与MapSethas方法类似:Map结构的has方法,是用来查找键名Set结构的has方法,是用来查找

3.6 flat和flatMap方法

Array.prototype.flat()用于将嵌套的数组“拉平”,变成一维的数组,对原数据没有影响。

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

flat方法可以有参数值,表示拉平的层数:默认为1,当为Infinity时,表示可以拉平任意层的嵌套数组。

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

若原数组有空位,flat方法会跳过空位。

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

flatMap方法是对原数组的每个成员执行一个函数(相当于执行Array.prototype.map()),然后对返回值组成的数组执行flat()方法。该方法的语法形式为:第一个参数为回调函数,第二个参数用来绑定遍历函数里的this

arr.flatMap(function callback(currentValue[, index[, array]]) {
  // ...
}[, thisArg])

注意:flatMap()方法会返回一个新数组,但并不会改变原数组,且只能展开一层数组

举例如下:

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

4 ES6对空位的处理

ES6会将空位转为undefined。如下所示:由于空位的处理规则非常不统一,所以建议不要出现空位

  1. Array.from方法会将数组的空位,转为undefined
  2. 扩展运算符...也会将空位转为undefined
  3. copyWithin()会连空位一起拷贝;
  4. fill()方法会将空位视为正常的数组位置;
  5. for...of循环也会遍历空位。

ES5大多数情况下会忽略空位,例如forEachfilterreduceeverysome方法;像jointoString方法则会将空位视为undefined处理成空字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值