ES6 spread operator three dots (...)

    In the React or Vue project, you may have noticed that some places have begun to use ES6 extension operators ..., this operator is very concise, if you are not familiar, you may find it difficult to understand, here is a little introduction to the extension operator Usage.

    The ES6 extension operator simplifies the problem of array or object assignment. Taking the object type as an example, when we first made an object copy, we need to assign all the properties of an object to the new object one by one, if the new object has other properties , You need to set:

var obj = {id:1,name:'buejee'}
var obj2 = {};
for( var key in obj){
  obj2[key] = obj[key]
}
obj2.age = 18;
console.log(obj)
console.log(obj2)

     Running this js, we get the results as follows:

    { id: 1, name: 'buejee' }
    { id: 1, name: 'buejee', age: 18 }

    When we have the ES6 extension operator, the assignment problem becomes very simple, only one step can be assigned successfully.    

const obj = {id:1,name:'buejee'}
const obj2 = {...obj,age:18}
console.log(obj)
console.log(obj2)

    Running this code can also get the above result.

    From this example, we can see that the spread operator ... split the object obj = {id: 1, name: 'buejee'} as if it were split into a collection of attributes, and did not use {nested }, If you use obj alone, the result is this:

   

    It can be seen from the screenshot that obj is used directly instead of ... obj, and the final obj2 nests the obj object.

    Similarly, the expansion operator is used in array assignments and has a similar function. Extract each element of the array separately and splice it into a new array.

arr = [1,2,3]
arr2 = [...arr,4,5,6]
console.log(arr)
console.log(arr2)

    Running this code, the result is as follows:

    [ 1, 2, 3 ]
    [ 1, 2, 3, 4, 5, 6 ]

    The above is to use the expansion operator to do rvalue assignment. In fact, he can also do lvalue assignment. In the case of lvalue, it is similar to subtraction, assigning the remaining part of the object or array to the new variable. Let's take a look at the following example:    

const obj = {id:1,name:'buejee',age:18}
let {id,...info} = obj
console.log(id)
console.log("info =",info)
let [a,b,...c]=[1,2,3,4,5]
console.log(a)
console.log(b)
console.log(c)

    The result of running this code is as follows:

    1
    info = { name: 'buejee', age: 18 }
    1
    2
    [ 3, 4, 5 ]

     Through the above simple examples, we can basically figure out the usage of the expansion operator, which is really convenient to use. It's a little difficult to understand. What we need to pay attention to in practical application is not to confuse objects and arrays.

Published 529 original articles · praised 287 · 1.47 million views

Guess you like

Origin blog.csdn.net/feinifi/article/details/103695922
Recommended