清空和截短數(shù)組
最簡(jiǎn)單的清空和截短數(shù)組的方法就是改變 length 屬性:

使用對(duì)象結(jié)構(gòu)模擬命名參數(shù)
以前,當(dāng)我們希望向一個(gè)函數(shù)傳遞多個(gè)參數(shù)時(shí),可能會(huì)采用配置對(duì)象的模式:

這是一個(gè)古老但是有效的模式,有了 ES2015 的對(duì)象結(jié)構(gòu),你可以這樣使用:

如果你需要這個(gè)配置對(duì)象參數(shù)變成可選的,也很簡(jiǎn)單:

數(shù)組的對(duì)象解構(gòu)
使用對(duì)象解構(gòu)將數(shù)組項(xiàng)賦值給變量:

注:本例中,2 為 split 之后的數(shù)組下標(biāo),country 為指定的變量,值為 US
switch 語(yǔ)句中使用范圍
這是一個(gè)在 switch 語(yǔ)句中使用范圍的例子:

await 多個(gè) async 函數(shù)
await 多個(gè) async 函數(shù)并等待他們執(zhí)行完成,我們可以使用 Promise.all:

創(chuàng)建純對(duì)象
你可以創(chuàng)建一個(gè) 100% 的純對(duì)象,這個(gè)對(duì)象不會(huì)繼承 Object 的任何屬性和方法(比如 constructor,toString() 等):

格式化 JSON 代碼
JSON.stringify 不僅可以字符串化對(duì)象,它也可以格式化你的 JSON 輸出:
移除數(shù)組重復(fù)項(xiàng)
使用 ES2015 和擴(kuò)展運(yùn)算符,你可以輕松移除數(shù)組中的重復(fù)項(xiàng):

注:只適用于數(shù)組內(nèi)容為基本數(shù)據(jù)類型
扁平化多維數(shù)組
使用擴(kuò)展運(yùn)算符可以快速扁平化數(shù)組:

不幸的是,上面的技巧只能適用二維數(shù)組,但是使用遞歸,我們可以扁平化任意緯度數(shù)組:

作者:黑馬程序員前端與移動(dòng)開(kāi)發(fā)培訓(xùn)學(xué)院
首發(fā):http://web.itheima.com/