像其它語言同樣,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"
相比以前使用起來更加容易了.