The spread operator (...) and the remaining operator (...) in JS


1. Concept

In JS, the spread operator (spread) is three points (...), and the rest operator (rest) is also three points(...)

Second, the spread operator

The main function of the spread operator is to convert an array into a sequence of parameters separated by commas, which is like the inverse operation of 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"]

Three, the remaining operator

Combine sequences of values ​​separated by commas into an array

//当函数参数个数不确定时,用 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]

Four, summary

The spread operator (spread) is represented by three dots, and its function is to expand an array or array-like object into a series of values ​​separated by commas.

The rest operator (rest) is also three dots, but its function is exactly the opposite of the spread operator, combining a sequence of values ​​separated by commas into an array.

When the three dots (...) are on the left side of the equal sign, or placed on a formal parameter, it is the rest operator

When three are on the right side of the equal sign, or on the actual parameter, it is the spread operator

In other words: the rest operator is placed on the assigned side. Put the spread operator in the assignment one way.


Five, reference materials

Array extension-Introduction to ECMAScript 6

Detailed explanation of spread operator (spread) and remaining operator (rest) in ES6

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/113030814