Home  >  Article  >  Web Front-end  >  What do multiple dots mean in JavaScript?

What do multiple dots mean in JavaScript?

青灯夜游
青灯夜游Original
2021-09-02 16:53:191891browse

In JavaScript, multiple dots "..." refer to the spread operator, which is a newly added feature in ES6. It can convert array expressions or String is expanded at the syntax level; object expressions can also be expanded in a "key-value" manner when constructing literal objects.

What do multiple dots mean in JavaScript?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In JavaScript, the three dots (...) are really called the spread operator, which is a new addition in ES6. It can add an array expression or string to the function call/array construction. Expansion at the syntax level; you can also expand the object expression in a key-value manner when constructing a literal object

Literals generally refer to [1,2,3] or {name:'chuichui' }With this simple construction method, the three points of multi-layered nested arrays and objects are powerless.

To put it bluntly, it means taking off the clothes, whether it is braces ([]), curly braces ({}), don’t worry about it, take them all off!

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

What’s the use?

Its use is very wide, we can see it everywhere, here are a few common examples

Copy and use it

//数组的复制
var arr1 = ['hello']
var arr2 =[...arr1]
arr2 // ['hello']
//对象的复制
var obj1 = {name:'chuichui'}
var obj2 ={...arr}
ob12 //  {name:'chuichui'}

Merge and use it

//数组的合并
var arr1 = ['hello']
var arr2 =['chuichui']
var mergeArr = [...arr1,...arr2]
mergeArr  // ['hello','chuichui']
// 对象分合并
var obj1 = {name:'chuichui'}
var obj2 = {height:176}
var mergeObj = {...obj1,...obj2}
mergeObj // {name: "chuichui", height: 176}

Use it to convert characters to arrays

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

Use it to pass function parameters

Can be combined with normal functions and used flexibly

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

When we want to use arrays Use it when the elements in iterate as function parameters!

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

// 以前的方法
f.apply(null,args);

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of What do multiple dots mean in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn