發(fā)布于:2021-01-16 15:51:24
0
63
0
就像所有其他編程語言一樣,JavaScript具有許多技巧來完成簡單和困難的任務。有些技巧眾所周知,而另一些技巧足以使您震驚。讓我們來看看您今天可以開始使用的七個JavaScript技巧!
獲取數(shù)組的唯一值
獲取唯一值數(shù)組可能比您想象的要容易:
var j = [...new Set([1, 2, 3, 3])] >> [1, 2, 3]
我喜歡rest表達和Set的混合!
數(shù)組和布爾
是否需要從數(shù)組中過濾假值(0,未定義,null, false等)?你可能不知道這個技巧:
myArray .map(item => { // ... }) // Get rid of bad values .filter(Boolean);
只要傳遞布爾值,所有的假值都消失!
創(chuàng)建空對象
當然,你可以用{}創(chuàng)建一個看起來是空的對象,但該對象仍然有__proto__和通常的hasOwnProperty和其他對象方法。然而,有一種方法可以創(chuàng)建一個純“dictionary”對象:
let dict = Object.create(null); // dict.__proto__ === "undefined" // No object properties exist until you add them
對象上沒有任何鍵或方法是你不放進去的!
合并對象
在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", } */
這三個點讓任務變得簡單多了!
需要函數(shù)參數(shù)
能夠為函數(shù)參數(shù)設置默認值對JavaScript來說是一個很棒的附加功能,但是看看這個技巧,它要求為給定的參數(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使用!
解構的別名
對JavaScript來說,解構是一個非常受歡迎的附加功能,但有時我們更喜歡用另一個名字來引用這些屬性,這樣我們就可以利用別名:
const obj = { x: 1 }; // Grabs obj.x as { x } const { x } = obj; // Grabs obj.x as { otherName } const { x: otherName } = obj;
獲取查詢字符串參數(shù)
多年來,我們編寫了大量的正則表達式來獲取查詢字符串值,但這些日子已經(jīng)一去不復返了——輸入令人驚嘆的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"
比我們以前編寫容易多了!
這些年來JavaScript已經(jīng)發(fā)生了很大的變化,但我最喜歡的部分是這些天來我們所看到的語言改進的速度。盡管JavaScript的動態(tài)變化不斷,我們仍然需要使用一些不錯的技巧;把這些技巧放在你的工具箱里,以備不時之需!
你最喜歡的JavaScript技巧是什么?
作者介紹