Home >Web Front-end >JS Tutorial >Detailed explanation of how to use the es6 three-dot operator
This article mainly brings you an article based on the use of the three-dot operator (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Let’s first look at an example of using the three-dot operator under the es6 specification:
let fun=function(a,...list){ console.log(a,list); }; fun('0','a','b','c');//0 [a,b,c]
As you can see from the above, we can now dynamically set the number of parameters when defining a function object: The first parameter a is a normal parameter (ignored).
You can see that there are three dots "..." in front of the second parameter list. This writing method has two uses in the es6 specification
1 . Used as a parameter.
2 . Used as a spread operator.
● Three dots--as parameters:
let fun1=function(...args){ for(let arg of args){ console.log(arg); }; console.log(args) }; fun1('a','b','c');//a b c,[a,b,c] fun1(1,2);//1 2,[1,2] ...args表示了所有的形参,不管传入多少参数,都可以通过args进行遍历得到,args则集合所有的参数组成参数数组 let fun2=function(arr,...args){ console.log(arr); console.log(args); }; fun2(1,2,3);//1, [2,3] fun2(1);//1, []当...args有其他参数时,rest参数args数组集合除去前面参数之后的参数。 let fun3=function(arr1,..args,arr2){ console.log(args); }//此时报错!切记,三点作为rest参数的时候,其后不能再有任何参数,只能作为最后一个角色出现! [x,...y]=[1,2,3]; console.log(y);//[2,3] [x,...y,z]=[1,2,3];//报错,Rest element must be last element in array //作为参数,三点运算符可以函数,解构赋值等方面发挥重要作用。‘人如其名',rest表示剩下的, //它把剩下的任意数量的参数推入数组,所以也继承了数组的方法。rest参数只能出现在最后一位, //不然会报错,当然以扩展运算的身份出现时另当别论。
● Three dots--used as expansion operators:
let arr=[1,2,3]; console.log(...arr);//1, 2, 3返回数组中的各项 let a=[2,3]; console.log(1,...a,4);//1,2,3,4扩展运算符可以放在中间 let ps=document.querySelectorAll('p'); [...ps];//Array[300],[]可以将ps转为数组解构; console.log(...ps);//p1,p2....遍历ps各项 let set=new Set([1,2,3,3]); [...set];//返回数组[1,2,3],可以将set数据结构转化为数组 let map=new Map([[1,'a'],[2,'b'],[3,'c']]); [...map.keys];//返回[1,2,3],属性数组; [...map.values];//返回[a,b,c],value数组 [...'wbiokr'];//["w", "b", "i", "o", "k", "r"]遍历字符串,返回各个字符; let str='abc'; ['aaa',...str,'ccc'];//[aaa, a, b, c, ccc]扩展运算符位置比较任性 //三点的扩展运算符,把数组或者类数组对象展开成一系列逗号隔开的值序列,它好比rest参数时候的逆运算。
Related recommendations:
How to use the three-dot operator
How to use the ES6 expansion operator
The above is the detailed content of Detailed explanation of how to use the es6 three-dot operator. For more information, please follow other related articles on the PHP Chinese website!