就如其餘的編程語言同樣,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);
複製代碼
例如:bash
console.log([1,0,null].filter(Boolean));
//輸出:[1]
複製代碼
你通常會使用{}
來建立一個空對象,可是這個對象其實仍是會有__proto__特性和hasOwnProperty
方法以及其餘方法的。數據結構
var o = {}
複製代碼
例若有一些對象方法: app
可是建立一個純「字典」對象,能夠這樣實現:編程語言
let dict = Object.create(null);
// dict.__proto__ === "undefined"
// 對象沒有任何的屬性及方法
複製代碼
合併多個對象這個使用展開運算符(...)便可簡單實現:函數
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;
複製代碼
使用URLSearchParams
API能夠輕鬆獲取查詢字符串各項的值:
// 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"
複製代碼
(完)