spread operator...

1. Meaning

1. Convert an array to a sequence of parameters separated by commas.
Note that only when the function is called, the spread operator can be placed in parentheses, otherwise an error will be reported.

console.log(...[1, 2, 3])
// 1 2 3
console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number
[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]

2. This operator is mainly used for function calls . This operator turns an array into a sequence of arguments.

function add(x, y) {
    
    
  return x + y;
}

const numbers = [4, 38];
add(...numbers) // 42

2. The apply() method of the alternative function

apply() in detail
Function: The apply( ) method calls a function with a given this value, and the parameters provided as an array (or array-like object).
Parameters: There are 2 parameters in total, both of which are optional.
The first parameter:
this points to. (this may not be the actual value seen by this method: if this function is in non-strict mode, when it is specified as null or undefined, it will be automatically replaced with a pointer to the global object, and the original value will be wrapped.) The second parameter:
an
array or an array-like object. (The array elements will be passed to the func function as separate parameters. If the value of the parameter is null or undefined, it means that no parameters need to be passed in.) If no parameters are passed: it is a global
variable


Since the spread operator can expand arrays, the apply() method is no longer needed to convert arrays into function parameters.

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

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

// 等同于
Math.max(14, 3, 77);
// ES5 的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);

// ES6 的写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
// ES5
new (Date.bind.apply(Date, [null, 2015, 1, 1]))

// ES6
new Date(...[2015, 1, 1]);

3. Application of spread operator

(1) Copy the array

An array is a composite data type. If you copy it directly, you just copy the pointer to the underlying data structure instead of cloning a brand new array.

An array is a composite data type. If you copy it directly, you just copy the pointer to the underlying data structure instead of cloning a brand new array.

const a1 = [1, 2];
const a2 = a1;

a2[0] = 2;
a1 // [2, 2]

In the above code, a2 is not a clone of a1, but another pointer pointing to the same data. Modifying a2 will directly lead to the change of a1.

ES5 can only use workarounds to copy arrays.

const a1 = [1, 2];
const a2 = a1.concat();

a2[0] = 2;
a1 // [1, 2]

In the above code, a1 will return a clone of the original array, and modifying a2 will not affect a1.

The spread operator provides a convenient way to copy an array.

const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;

In the above two ways of writing, a2 is a clone of a1.

(2) Merge arrays

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

// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]

However, these two methods are shallow copies, and you need to pay attention when using them.

const a1 = [{
    
     foo: 1 }];
const a2 = [{
    
     bar: 2 }];

const a3 = a1.concat(a2);
const a4 = [...a1, ...a2];

a3[0] === a1[0] // true
a4[0] === a1[0] // true

In the above code, a3 and a4 are new arrays merged by two different methods, but their members are all references to the original array members, which is shallow copy. If the value pointed to by the reference is modified, it will be reflected in the new array synchronously.

(3) Combined with destructuring assignment

The spread operator can be combined with destructuring assignment to generate arrays.

// ES5
a = list[0], rest = list.slice(1)

// ES6
[a, ...rest] = list

If the spread operator is used for array assignment, it can only be placed in the last position of the parameter, otherwise an error will be reported.

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

(4) string

The spread operator can also convert strings into real arrays.

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

Four-byte Unicode characters are correctly recognized.
JavaScript recognizes four-byte Unicode characters as two characters, and there is no such problem with the spread operator. Therefore, a function that correctly returns the length of a string can be written as follows.

'x\uD83D\uDE80y'.length // 4
[...'x\uD83D\uDE80y'].length // 3

function length(str) {
    
    
  return [...str].length;
}

length('x\uD83D\uDE80y') // 3

(5) Objects that implement the Iterator interface

Guess you like

Origin blog.csdn.net/weixin_53125679/article/details/124295441