一些比較有用的 JS 技巧

1、數組去重

const j = [...new Set([1, 2, 3, 3])];

console.log(j); // [ 1, 2, 3 ]

2、過濾錯誤值

0undefinednullfalse 等錯誤值從數組中剔除:

myArray
  .map(item => {
    // ...
  })
  // Get rid of bad values
  .filter(Boolean);

3、創建一個空對象

你當然可以使用 {} 來創建一個空對象,但是這個對象依舊有 __proto__hasOwnProperty 和對象上的一些其它方法。可以這樣創建一個純的空對象:

let dict = Object.create(null);

// dict.__proto__ === "undefined"
// No object properties exist until you add them

4、合併對象

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",
}
*/

5、Require Function Parameters

const isRequired = () => {
  throw new Error('param is required');
};

const hello = (name = isRequired()) => {
  console.log(`hello ${name}`);
};

// This will throw an error because no name is provided
hello();

// This will also throw an error
hello(undefined);

// These are good!
hello(null);
hello('David');

6、爲解構賦值添加別名

const obj = { x: 1 };

// Grabs obj.x as { x }
const { x } = obj;

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

7、獲取查詢字符串參數

// Assuming "?post=1234&action=edit"

const 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"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章