ES6 数组的扩展:扩展运算符

文章目录

扩展运算符

扩展运算符(…)作用是将一个数组转为用逗号分隔的参数序列。

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

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

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

function _push(arr, ...items) { // 这里的 ...items 将会以数组的形式接收所有剩余的参数
	console.log(items);  // [2, 3]
	arr.push(...items);
}

_push([1], 2, 3]);  // [1, 2, 3]

如果该运算符后面是一个空数组,则不产生任何效果:

console.log(...[]);  // 空
console.log([...[], 1]);  // [1]

应用

1️⃣ 求数组最大与最小元素

// ES5
Math.max.apply(null, arr);

// ES6
Math.max(...arr);

2️⃣ 将一个数组添加到另一个数组的尾部

// ES5
Array.prototype.push.apply(arr1, arr2);

// ES6
arr1.push(...arr2);

3️⃣ 复制数组

// ES5
const arr2 = arr1.concat();

// ES6
const arr2 = [...arr1];
// 写法二
const [...arr2] = arr1

4️⃣ 合并数组

// ES5
arr1.concat(arr2, arr3);

// ES6
[...arr1, ...arr2, ...arr3];

5️⃣ 与解构赋值结合

const [first, ...rest] = [1, 2, 3];
first // 1
rest  // [2, 3]

const [first, ...rest] = [];
first // undefined
rest  // []

如果将扩展运算符用于数组赋值时,只能放在参数的最后一位,否则报错:

const [...rest, last] = [1, 2, 3];   // 报错

6️⃣ 字符串

扩展运算符可以将字符串转为真正的数组:

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

7️⃣ 定义了遍历器(Iterator)接口的对象,都可以用扩展运算符转为真正的数组。

let nodeList = document.querySelectAll('div');
let arr = [...nodeList];

对于那些没有部署 Iterator 接口的类似数组的对象,扩展运算符就无法将其转为真正的数组。

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

// TypeError: Cannot spread non-iterable object.
let arr = [...arrayLike];

参考文章

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值