超实用ES6小技巧,赶快Mark起来!
- 日期:2020-04-01
- 浏览:1,568次
作为当下越来越热门的ES6,ES6有许多技巧用来解决简单和复杂的问题。有些技巧广为人知,还有一些会让人兴奋不已。让我们看一下今天可以学习到的7个ES6技巧!
01、获取数组的唯一值
得到一个唯一值数组可能比你想的还要容易:
02、数组和Boolean
如果需要把数组中的0、undefined、null、false等等排除掉,可以使用以下技巧:
myArray
.map(item => {
return item;
})
// 去除所有假值
.fliter(Boolean)
只要需要在filter方法中传递Boolean,所有的虚假值就可以被过滤掉。
03、创建空对象
创建一个空的对象,可以使用{}方式。但是这种方式创建的对象依然包含proto、hasOwnProperty和其它一些对象方法。我们还有其它方法创建一个纯空对象:
let obj = Object.create(null);
// obj.__proto__ === "undefined" // false
使用create方法创建出现的对象,不包含任意的属性或者方法,把这些代码添加到对象中去。
04、合并对象
对需要把多个对象合并为一个对象时,特别是当我们开始使用选项创建类和小组件时:
const person = {name: 'David walsh', gender: 'Male'};
const tools = {computer: 'Mac', editor: 'Atom'};
const attributes = {handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue'};
const summary = {…person, …tools, …attributes};
/*
{
"computer": "Mac",
"editor": "Atom",
"eyes": "Blue",
"gender": "Male",
"hair": "Brown",
"handsomeness": "Extreme",
"name": "David walsh"
}
*/
这三个点使任务变得轻松多了!
05、要求提供函数参数
通过给函数的参数设置默认值,可以不写某些参数的值,调用时会自动把默认值传递给调用语句中。如果使用时必须提供某个参数的值可以使用下面的技巧:
const isRequired = () => {throw new Error('param is required');};
const hello = (name = isRequired()) => {console.log(`hello ${name}`)};
// 这会产生一个异常信息
hello();
// 这也会产生一个异常信息
hello(undefined);
// 以下方式可以正常运行
hello(null);
hello('David');
06、解构别名
解构赋值是ES6的新特性,这是一个非常实用的功能。但有时我们希望使用另一个变量名来引用这些属性,这时可以使用别名:
const obj = {x: 1};
// 变量x等同于obj的x
const {x} = obj;
// 变量otherName等同于obj的x
const {x: otherName} = obj;
这样做可以有效避免与现有变量的命名发生冲突。
07、获取查询字符串参数
如果我们需要处理URL的查询字符串,需要编写大量的正则表达式。使用URLSearchParamsAPI会使这个过程简单多了:
// 假设URL的查询字符串是: ?post=1234&action=edit
var urlParams = new URLSearchParams(window.location.search);
// 是否包含post的key
console.log(urlParams.has('post')); // true
// 获取key是action的第1个值
console.log(urlParams.get('action')); // "edit"
// 获取key是action的所有值
console.log(urlParams.getAll('post')); //["edit"]
// 返回搜索参数组成的字符串
console.log(urlParams.toString('post')); // "?post=1234&action=edit"
// 插入一个指定的键值对作为新的参数
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
近些年JavaScript已经发生了很大的变化,值得庆幸的是我们能看到JavaScript语言改进的速度非常之快。尽管JavaScript不断地在变化,我们仍然需要保存一些不错的技巧,来帮助我们提高效率。