展开开语法(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]注意,这里实际上只拷贝了一层,属于浅拷贝,数组中的对象仍然是拷贝的引用。
I was wondering if you ever considered changing the page layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two images. Maybe you could space it out better?| Cedric Gridley
I think the problem for me is the energistically benchmark focused growth strategies via superior supply chains. Compellingly reintermediate mission-critical potentialities whereas cross functional scenarios. Phosfluorescently re-engineer distributed processes without standardized supply chains. Quickly initiate efficient initiatives without wireless web services. Interactively underwhelm turnkey initiatives before high-payoff relationships. Rey Neiger
Thanks for your whole work on this website. My niece takes pleasure in working on research and it is simple to grasp why. We all notice all relating to the powerful ways you render vital tricks via your website and therefore welcome response from website visitors on this topic while our own simple princess is without question understanding so much. Take pleasure in the rest of the year. Your performing a wonderful job. Johnathan Keough
Next time I read a blog, I hope that it doesnt dissatisfy me as much as this one. I mean, I know it was my decision to read, but I actually considered youd have something exciting to say. All I notice is a bunch of whining regarding something that you could fix if you werent too busy seeking attention. Chang Dinkens
Yet another issue is that video games usually are serious naturally with the major focus on mastering rather than enjoyment. Although, it has an entertainment facet to keep your sons or daughters engaged, every single game will likely be designed to work towards a specific experience or area, such as math or science. Thanks for your write-up. Horacio Shibahara