7个有用的JavaScript技巧

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

数组去重

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

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

Set的详细用法能够查看ES6入门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方法以及其余方法的。app

var o = {}

例若有一些对象方法:
编程语言

可是建立一个纯“字典”对象,能够这样实现:函数

let dict = Object.create(null);

// dict.__proto__ === "undefined"
// 对象没有任何的属性及方法

合并对象

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

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')); // 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"

(完)

参考

原文连接
默认参数

相关文章
相关标签/搜索