值得收藏 7 个有用JavaScript技巧

像其它语言一样,JavaScript中也可以通过一些技巧来完成一些复杂的操作. 接下来我们学习吧

数组去重

    var arr = [1, 2, 3, 3, 4];    console.log(...new Set(arr))    >> [1, 2, 3, 4]

数组和布尔

有时我们需要过滤数组中值为 false 的值. 例如(0, undefined, null, false), 你可能不知道这样的技巧

 var myArray = [1, 0 , undefined, null, false]; myArray.filter(Boolean); >> [1]

是不是很简单, 只需要传入一个 Boolean 函数即可.

创建一个空对象

有时我们需要创建一个纯净的对象, 不包含什么原型链等等. 一般创建空对象最直接方式通过字面量 {}, 但这个对象中依然存在 __proto__ 属性来指向 Object.prototype 等等.

    let dict = Object.create(null);    dict.__proto__ === "undefined" 

合并对象

在JavaScript中合并多个对象的需求一直存在, 比如在传参时需要把表单参数和分页参数进行合并后在传递给后端

    const page = {        current: 1,        pageSize: 10    }    const form = {        name: "",        sex: ""    }    const params = {...form, ...page};    /*        {            name: "",            sex: "",            current: 1,            pageSize: 10        }    *

利用ES6提供的扩展运算符让对象合并变得很简单.

函数参数必须

ES6中可以给参数指定默认值,确实带来很多便利. 如果需要检测某些参数是必传时,可以这么做

    const isRequired = () => { throw new Error('param is required'); };    const hello = (name = isRequired()) => { console.log(`hello ${name}`) };    // 这里将抛出一个错误,因为名字时必须    hello();    // 这也将抛出一个错误    hello(undefined);    // 正常    hello(null);    hello('David'); 

解构赋值时使用别名

解构赋值是一个非常受欢迎的JavaScript功能,但有时我们更喜欢用其他名称引用这些属性,所以我们可以利用别名来完成:

    const obj = { x: 1 };    // Grabs obj.x as { x }    const { x } = obj;    // Grabs obj.x as { otherName }    const { x: otherName } = obj;

获取查询参数

多年来,我们编写粗糙的正则表达式来获取查询字符串值,但那些日子已经一去不复返了; 现在我们可以通过 URLSearchParams API 来获取查询参数

在不使用 URLSearchParams 我们通过正则的方式来完成获取查询参数的, 如下:

  function getQueryString(name) {    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");    var r = window.location.search.substr(1).match(reg);    return r ? r[2] : null;  }

使用 URLSearchParams 之后:

    // 假设地址栏中查询参数是这样 "?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"

相比之前使用起来更加容易了.