What are the three dots (…) in JS?

Time:2020-9-19

When we look at JS code, we often have (…) three dots. What does it mean? What’s the use?
Now I’d like to share with you three things

what do you mean?

The three dot (…) is called extension operator, which is a new content in ES6. It can expand array expression or string in syntax level when function call / array construction; it can also expand object expression according to key value when constructing literal object

Literal quantity generally refers to [1,2,3] or {Name: ‘Chuichui’} this kind of concise construction method, multi-layer nested array and object three points can’t help

To put it bluntly, it means to take off your clothes. Whether it’s braces (()) or curly braces ({}), it’s all right,Take it all off! Take it off!

//Array
var number = [1,2,3,4,5,6]
console.log(...number) //1 2 3 4 5 6
//Object
var man = {name:'chuichui',height:176}
console.log({...man}) / {name:'chuichui',height:176}

What’s the usage?

It has a wide range of uses, and we can see it everywhere. Here are a few common examples

Copy it

//Copying arrays
var arr1 = ['hello']
var arr2 =[...arr1]
arr2 // ['hello']
//Replication of objects
var obj1 = {name:'chuichui'}
var obj2 ={...arr}
ob12 //  {name:'chuichui'}

Combine it

//Merging arrays
var arr1 = ['hello']
var arr2 =['chuichui']
var mergeArr = [...arr1,...arr2]
mergeArr  // ['hello','chuichui']
//Object splitting and merging
var obj1 = {name:'chuichui'}
var obj2 = {height:176}
var mergeObj = {...obj1,...obj2}
mergeObj // {name: "chuichui", height: 176}

Character to array, use it

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

Functions pass parameters with it

Can be combined with normal functions, flexible use

function f(v,w,x,y,z){ }
var args = [2,3]
f(1,...args,4,...[5])

When we want to iterate the elements of an array into function parameters, use it!

function f(x,y,z){}
var args = [1,2,3]
f(...args)

//Previous methods
f.apply(null,args);

feel

With three points feel that everything can be omitted, everything in silence, you slowly taste A kind of A kind of

last

Well, that’s all I have to share this time. If you think my article is helpful to you, please don’t be stingy with your praise, Amen~