每种编程语言都有一些“黑魔法”或者说小技巧,JS也不例外,大部分是借助ES6或者浏览器新特性实现。下面介绍的7个实用小技巧,相信其中有些你必定用过。javascript
const j = [...new Set([1, 2, 3, 3])] >> [1, 2, 3]
洗掉数组中一些无用的值,如 0, undefined, null, false
等前端
myArray .map(item => { // ... }) // Get rid of bad values .filter(Boolean);
咱们可使用对象字面量{}
来建立空对象,但这样建立的对象有隐式原型__proto__
和一些对象方法好比常见的hasOwnProperty
,下面这个方法能够建立一个纯对象。java
let dict = Object.create(null); // dict.__proto__ === "undefined" // No object properties exist until you add them
该方法建立的对象没有任何的属性及方法编程
JS中咱们常常会有合并对象的需求,好比常见的给用传入配置覆盖默认配置,经过ES6扩展运算符就能快速实现。数组
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}; /* Object { "computer": "Mac", "editor": "Atom", "eyes": "Blue", "gender": "Male", "hair": "Brown", "handsomeness": "Extreme", "name": "David Walsh", } */
借助ES6支持的默认参数特性,咱们能够将默认参数设置为一个执行抛出异常代码函数返回的值,这样当咱们没有传参时就会抛出异常终止后面的代码运行。浏览器
const isRequired = () => { throw new Error('param is required'); }; const hello = (name = isRequired()) => { console.log(`hello ${name}`) }; // This will throw an error because no name is provided hello(); // This will also throw an error hello(undefined); // These are good! hello(null); hello('David');
ES6中咱们常常会使用对象结构获取其中的属性,但有时候会想重命名属性名,以免和做用域中存在的变量名冲突,这时候能够为解构属性名添加别名。app
const obj = { x: 1 }; // Grabs obj.x as { x } const { x } = obj; // Grabs obj.x as as { otherName } const { x: otherName } = obj;
之前获取URL中的字符串参数咱们须要经过函数写正则匹配,如今经过URLSearchParams
API便可实现。编程语言
// Assuming "?post=1234&action=edit" var urlParams = new URLSearchParams(window.location.search); console.log(urlParams.has('post')); // true console.log(urlParams.get('action')); // "edit" console.log(urlParams.getAll('action')); // ["edit"] console.log(urlParams.toString()); // "?post=1234&action=edit" console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
随着Javascript的不断发展,不少语言层面上的不良特性都在逐渐移除或者改进,现在的一行ES6代码可能等于当年的几行代码。ide
拥抱JS的这些新变化意味着前端开发效率的不断提高,以及良好的编码体验。固然无论语言如何变化,咱们总能在编程中总结一些小技巧来精简代码。函数
本文首发于公众号「前端新视界」,若是你也有一些Javascript的小技巧,欢迎在下方留言,和你们一块儿分享哦!