值得收藏 7 个有用JavaScript技巧

值得收藏 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中合并多个对象的需求一直存在, 好比在传参时须要把表单参数和分页参数进行合并后在传递给后端app

const page = {
        current: 1,
        pageSize: 10
    }

    const form = {
        name: "",
        sex: ""
    }

    const params = {...form, ...page};

    /*
        {
            name: "",
            sex: "",
            current: 1,
            pageSize: 10

        }
    *

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

函数参数必须

ES6中能够给参数指定默认值,确实带来不少便利. 若是须要检测某些参数是必传时,能够这么作post

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 来获取查询参数ui

在不使用 URLSearchParams 咱们经过正则的方式来完成获取查询参数的, 以下:url

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

使用 URLSearchParams 以后:prototype

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

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

相关文章
相关标签/搜索