
每種編程語言都有一些“黑魔法”或者說小技巧,JS也不例外,大部分是借助ES6或者瀏覽器新特性實(shí)現(xiàn)。下面介紹的7個(gè)實(shí)用小技巧,相信其中有些你一定用過。
數(shù)組去重
const j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]
數(shù)組清洗
洗掉數(shù)組中一些無用的值,如0, undefined, null, false等
myArray
.map(item => {
// ...
})
// Get rid of bad values
.filter(Boolean);
創(chuàng)建空對象
我們可以使用對象字面量{}來創(chuàng)建空對象,但這樣創(chuàng)建的對象有隱式原型__proto__和一些對象方法比如常見的hasOwnProperty,下面這個(gè)方法可以創(chuàng)建一個(gè)純對象。
let dict = Object.create(null);
// dict.__proto__ === "undefined"
// No object properties exist until you add them
該方法創(chuàng)建的對象沒有任何的屬性及方法
合并對象
JS中我們經(jīng)常會(huì)有合并對象的需求,比如常見的給用傳入配置覆蓋默認(rèn)配置,通過ES6擴(kuò)展運(yùn)算符就能快速實(shí)現(xiàn)。
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ù)
借助ES6支持的默認(rèn)參數(shù)特性,我們可以將默認(rèn)參數(shù)設(shè)置為一個(gè)執(zhí)行拋出異常代碼函數(shù)返回的值,這樣當(dāng)我們沒有傳參時(shí)就會(huì)拋出異常終止后面的代碼運(yùn)行。
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');
解構(gòu)別名
ES6中我們經(jīng)常會(huì)使用對象結(jié)構(gòu)獲取其中的屬性,但有時(shí)候會(huì)想重命名屬性名,以避免和作用域中存在的變量名沖突,這時(shí)候可以為解構(gòu)屬性名添加別名。
const obj = { x: 1 };
// Grabs obj.x as { x }
const { x } = obj;
// Grabs obj.x as as { otherName }
const { x: otherName } = obj;
獲取查詢字符串參數(shù)
以前獲取URL中的字符串參數(shù)我們需要通過函數(shù)寫正則匹配,現(xiàn)在通過URLSearchParamsAPI即可實(shí)現(xiàn)。
// 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的不斷發(fā)展,很多語言層面上的不良特性都在逐漸移除或者改進(jìn),如今的一行ES6代碼可能等于當(dāng)年的幾行代碼。
擁抱JS的這些新變化意味著前端開發(fā)效率的不斷提升,以及良好的編碼體驗(yàn)。當(dāng)然不管語言如何變化,我們總能在編程中總結(jié)一些小技巧來精簡代碼。
PS:更多前端資訊、技術(shù)干貨,請關(guān)注公眾號(hào)「前端新視界」,后臺(tái)回復(fù) “1” 獲取100本PDF前端電子書
回復(fù) “2” 獲取小編精選的Python編程電子書
