7个有用的JS技巧

就如其他的编程语言一样,JavaScript也具有许多技巧来完成简单和困难的任务。 一些技巧已广为人知,而有一些技巧也会让你耳目一新。 让我们来看看今天可以开始使用的七个JavaScript技巧吧!

数组去重

使用ES6全新的数据结构即可简单实现。

var j = [...new Set([1, 2, 3, 3])]输出: [1, 2, 3]

Set的详细用法可以查看ES6入门

数组和布尔值

当数组需要快速过滤掉一些为false的值(0,undefined,false等)使,一般是这样写:

myArray .map(item => { // ... }) // Get rid of bad values .filter(item => item);

可以使用Boolean更简洁地实现

myArray .map(item => { // ... }) // Get rid of bad values .filter(Boolean);

例如:

console.log([1,0,null].filter(Boolean));//输出:[1]

创建纯空对象

你一般会使用{}来创建一个空对象,但是这个对象其实还是会有__proto__特性和hasOwnProperty方法以及其他方法的。

var o = {}

例如有一些对象方法:

但是创建一个纯“字典”对象,可以这样实现:

let dict = Object.create(null);// dict.__proto__ === "undefined"// 对象没有任何的属性及方法

合并对象

合并多个对象这个使用展开运算符(...)即可简单实现:

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",}*/

函数参数必传校验

函数设置默认参数是JS一个很好的补充,但是下面这个技巧是要求传入参数值需要通过校验。

const isRequired = () => { throw new Error('param is required'); };const hello = (name = isRequired()) => { console.log(`hello ${name}`) };// 没有传值,抛出异常hello();// 抛出异常hello(undefined);// 校验通过hello(null);hello('David');

函数默认参数允许在没有值或undefined被传入时使用默认形参。如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值。

解构别名

const obj = { x: 1 };// 通过{ x }获取 obj.x 值 const { x } = obj;// 设置 obj.x 别名为 { otherName }const { x: otherName } = obj;

获取查询字符串参数

使用URLSearchParamsAPI可以轻松获取查询字符串各项的值:

// Assuming "?post=1234&action=edit"var urlParams = new URLSearchParams(window.location.search);console.log(urlParams.has('post')); // trueconsole.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"

(完)

参考

原文链接
默认参数

相关文章