七個實用的JavaScript技巧

1、獲取數(shù)組的唯一值 (Get Unique Values of an Array)
獲取唯一值數(shù)組可能比想象的要容易:

var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]

2、數(shù)組和布爾 (Array and Boolean)
是否曾經(jīng)需要從數(shù)組中過濾出偽造的值 ( 0 , undefined , null , false等)?你可能不知道此技巧:

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

只需傳遞Boolean ,所有那些虛假的值就會消失!

3、創(chuàng)建空對象 (Create Empty Objects)
當(dāng)然,你可以使用{}創(chuàng)建一個似乎為空的對象,但是該對象仍然具有proto以及通常的hasOwnProperty和其他對象方法。但是,有一種方法可以創(chuàng)建一個純“字典”對象 :

let dict = Object.create(null);
 
// dict.__proto__ === "undefined"
// No object properties exist until you add them

沒有放置在該對象上的鍵或方法絕對沒有!

4、合并物件 (Merge Objects)
在JavaScript中合并多個對象的需求一直存在,尤其是在我們開始創(chuàng)建帶有選項的類和小部件時:

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

這三個點(diǎn)使任務(wù)變得如此簡單!

5、需要功能參數(shù) (Require Function Parameters)
能夠為函數(shù)參數(shù)設(shè)置默認(rèn)值是對JavaScript的一個很棒的補(bǔ)充,但是請查看以下技巧, 要求為給定參數(shù)傳遞值 :

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');

這是一些下一級的驗證和JavaScript的用法!

6、破壞別名 (Destructuring Aliases)
銷毀是JavaScript的一個非常受歡迎的附加功能,但是有時我們希望用另一個名稱來引用這些屬性,因此我們可以利用別名:

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

有助于避免與現(xiàn)有變量的命名沖突!

7、獲取查詢字符串參數(shù) (Get Query String Parameters)
多年以來,我們編寫了粗糙的正則表達(dá)式來獲取查詢字符串值,但是日子已經(jīng)一去不復(fù)返了
輸入URLSearchParams API:

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"

將這些技巧保存在工具箱中,已備需要時使用吧!
文章翻譯自: https://davidwalsh.name/javascript-tricks

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容