清空和截短数组
最简单的清空和截短数组的方法就是改变 length 属性:

使用对象结构模拟命名参数
以前,当我们希望向一个函数传递多个参数时,可能会采用配置对象的模式:

这是一个古老但是有效的模式,有了 ES2015 的对象结构,你可以这样使用:

如果你需要这个配置对象参数变成可选的,也很简单:

数组的对象解构
使用对象解构将数组项赋值给变量:

注:本例中,2 为 split 之后的数组下标,country 为指定的变量,值为 US
switch 语句中使用范围
这是一个在 switch 语句中使用范围的例子:

await 多个 async 函数
await 多个 async 函数并等待他们执行完成,我们可以使用 Promise.all:

创建纯对象
你可以创建一个 100% 的纯对象,这个对象不会继承 Object 的任何属性和方法(比如 constructor,toString() 等):

格式化 JSON 代码
JSON.stringify 不仅可以字符串化对象,它也可以格式化你的 JSON 输出:
移除数组重复项
使用 ES2015 和扩展运算符,你可以轻松移除数组中的重复项:

注:只适用于数组内容为基本数据类型
扁平化多维数组
使用扩展运算符可以快速扁平化数组:

不幸的是,上面的技巧只能适用二维数组,但是使用递归,我们可以扁平化任意纬度数组:

作者:黑马程序员前端与移动开发培训学院
首发:http://web.itheima.com/