展开开语法(Spread syntax)是属于 ES6 的一个新特性, 可以将数组表达式或者字符串在语法层面展开。用法:
myFunction(...iterableObj)接下来我们看看这个新特性到底有什么用
apply
下面的方法传入3个参数然后计算和
function sum (a,b,c) {
return a+b+c
}如果我们要传入的参数是一个数组呢?
var arr = [1,2,3]通常我们会用 apply() 来实现
sum.apply(null, arr)但是有了展开运算符我们实现起来就更简单了
sum(...arr)代码看起来是不是更简洁清晰了?
数组合并
合并数组的方法有很多,常用的是 concat()
var arr1 = [1,2]
var arr2 = [3,4]arr1 = arr1.concat(arr2)需要注意的是,concat是返回一个新的数组,并非修改原数组,所以还需要去接收返回值。
然而用 push (向数组的末尾添加一个或多个元素)结合展开运算符是能直接修改原数组的,非常酷炫
arr1.push(...arr2)或者追加到数组的开头
arr1.unshift(...arr2)有没有更变态的呢?把新数组添加到任意位置
var arr2 = [3, ...arr1, 4]非常灵活方便。
上面提到的
push()方法实际上是属于一类可接收任意数量参数的方法,而此类方法均可以使用展开运算符
比如 Math.min()
var nums = [4, 5, 3, 1]
Math.min(...nums)数组拷贝
var arr1 = [1,2]
var arr2 = [...arr1]注意,这里实际上只拷贝了一层,属于浅拷贝,数组中的对象仍然是拷贝的引用。
Well I truly liked reading it. This tip procured by you is very practical for correct planning. Joseph Benzschawel
I constantly emailed this website post page to all my friends, since if like to read it after that my links will too. Alden Rebar
Hello, I wish for to subscribe for this web site to get most recent updates, so where can i do it please assist. Otto Kebort
He nods confidently as he drapes the black garment over his neck. Danial Sevilla
Hey very nice site!! Guy .. Beautiful .. Wonderful .. Otis Borja