1. 程式人生 > >7個有用的JavaScript技巧

7個有用的JavaScript技巧

就如其他的程式語言一樣,JavaScript也具有許多技巧來完成簡單和困難的任務。 一些技巧已廣為人知,而有一些技巧也會讓你耳目一新。 讓我們來看看今天可以開始使用的七個JavaScript技巧吧!

陣列去重

使用ES6全新的資料結構即可簡單實現。

var j = [...new Set([1, 2, 3, 3])]
輸出: [1, 2, 3]

Set的詳細用法可以檢視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);

例如:

console.log([1,0,null].filter(Boolean));
//輸出:[1]

建立純空物件

你一般會使用{}來建立一個空物件,但是這個物件其實還是會有__proto__特性和hasOwnProperty方法以及其他方法的。

var o = {}

例如有一些物件方法:

但是建立一個純“字典”物件,可以這樣實現:

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;

獲取查詢字串引數

使用URLSearchParamsAPI可以輕鬆獲取查詢字串各項的值:

// 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"

(完)

參考

原文連結
預設參