JS中的扩展运算符(...)和剩余运算符(...)

一、概念

在JS中,扩展运算符(spread)是三个点 (...) ,剩余运算符(rest)也是三个点 (...)

二、扩展运算符

(1)基本使用:扩展运算符的主要作用是将一个数组转为用逗号分隔的参数序列,它好比 rest 的逆运算

//传递数据代替多个字符串的形式
function  test(a,b,c){
  console.log(a); // 1
  console.log(b); // 2
  console.log(c); // 3
}

var arr = [1, 2, 3];
test(...arr);

//将一个数组插入到另一个数组中
var arr1 = [1,2,3];
var arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // [1, 2, 3, 4, 5, 6]

//字符串转数组
var str = 'hello';
var arr3 = [...str];
console.log(arr3); // ["h", "e", "l", "l", "o"]

(2)扩展运算符(…)会调用默认的 Iterator 接口。

// 例一
var str = 'hello';
[...str] //  ['h','e','l','l','o']

// 例二
let arr = ['b', 'c'];
['a', ...arr, 'd']
// ['a', 'b', 'c', 'd']

上面代码的扩展运算符内部就调用 Iterator 接口。

实际上,这提供了一种简便机制,可以将任何部署了 Iterator 接口的数据结构,转为数组。也就是说,只要某个数据结构部署了 Iterator 接口,就可以对它使用扩展运算符,将其转为数组。

let arr = [...iterable];

有关对 Iterator 的介绍,请查看这篇文章 ES6中的Iterator(遍历器)和 for of 循环

(3)由于扩展运算符可以展开数组,所以可以用来替代函数的 apply 方法

// ES5 的写法
function f(x, y, z) {
  // ...
}
var args = [0, 1, 2];
f.apply(null, args);

// ES6 的写法
function f(x, y, z) {
  // ...
}
let args = [0, 1, 2];
f(...args);

下面是扩展运算符取代 apply 方法的一个实际的例子,应用 Math.max 方法,简化求出一个数组最大元素的写法。

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

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

// 等同于
Math.max(14, 3, 77);

三、剩余运算符

把用逗号隔开的值序列组合成一个数组

//当函数参数个数不确定时,用 rest运算符
function f1(...args) {
  console.log(args); // [1,2,3]
}

f1(1,2,3);

//当函数参数个数不确定时的第二种情况
function f2(item, ...arr) {
  console.log(item); // 1
  console.log(arr);  // [2,3]
}
f2(1, 2, 3);

//rest运算符配合 解构使用
let [a,...temp]=[1, 2, 4];
console.log(a);    // 1
console.log(temp); // [2,4]

四、总结

扩展运算符(spread)用三个点号表示,功能是把数组或类数组对象展开成一系列用逗号隔开的值。

剩余运算符(rest)也是三个点号,不过其功能与扩展运算符恰好相反,把逗号隔开的值序列组合成一个数组。

当三个点(…)在等号左边,或者放在形参上,为 rest 运算符

当三个在等号右边,或者放在实参上,是 spread运算符

或者说:放在被赋值一方是rest 运算符。放在赋值一方式 spread运算符。

 
posted @ 2024-01-24 18:04  一统天下。  阅读(33)  评论(0编辑  收藏  举报