Spread_Operator

Spread Operator

Deconstruct the values in the array, suitable for the comma separation (this applies to all iterables)

  • Iterables:arrary, strings, maps, sets.Not objects
  • Usually separated by commas: a function passes arguments, builds a new array
1
2
3
4
const arr = [7, 8, 9];
const newArr = [1, 2, ...arr];
console.log(newArr);//(5) [1, 2, 7, 8, 9]
console.log(...newArr);//1 2 7 8 9

Application

  • Shallow copy

    • ``` js
      let newArr = […oldArr];
      1
      2
      3
      4
      5

      - Combine arrays

      - ``` js
      const Arr = [...Arr1,...Arr2];
1
console.log(..."jonas");//j o n a s

Specially

  • Works for object, too.
1
let newObj = { ...oldObj,name:"tom"}

以此来实现对象的浅拷贝

Rest Pattern

It’s similar to the spread pattern, but the three dots are on the left.

Example:

1
2
const [a, b, ...others] = [1, 2, 3, 4, 5, 6];
console.log(a, b, others);//1 2 (4) [3, 4, 5, 6]

the Rest element must be the last one in [].

Of course, object can use it too.

In Function

1
2
3
4
5
6
const [a, b, ...others] = [1, 2, 3, 4, 5, 6];
console.log(a, b, others);
const add = function (...numbers) {
console.log(numbers);
};
add(1, 2, 3, 45, 6, 56, 45, 755, 3, 57);//(10) [1, 2, 3, 45, 6, 56, 45, 755, 3, 57]

本站由 @Eureka 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。