es6 7個比較有用的技巧

數組去重

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

數組和布爾

有時咱們須要過濾數組中值爲 false 的值. 例如(0, undefined, null, false), 你可能不知道這樣的技巧javascript

var myArray = [1, 0 , undefined, null, false];
myArray.filter(Boolean);
> > [1]
//是否是很簡單, 只須要傳入一個 Boolean 函數便可.

建立一個空對象

有時咱們須要建立一個純淨的對象, 不包含什麼原型鏈等等. 通常建立空對象最直接方式經過字面量 {}, 但這個對象中依然存在 proto 屬性來指向 Object.prototype 等等.java

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功能,但有時咱們更喜歡用其餘名稱引用這些屬性,因此咱們能夠利用別名來完成:app

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

獲取查詢參數

多年來,咱們編寫粗糙的正則表達式來獲取查詢字符串值,但那些日子已經一去不復返了; 如今咱們能夠經過 URLSearchParams API 來獲取查詢參數函數

在不使用 URLSearchParams 咱們經過正則的方式來完成獲取查詢參數的, 以下:post

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

使用 URLSearchParams 以後:ui

// 假設地址欄中查詢參數是這樣 "?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"

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

相關文章
相關標籤/搜索