當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
15个JavaScript 编码小技巧
生活随笔
收集整理的這篇文章主要介紹了
15个JavaScript 编码小技巧
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
三元操作符 ? ? ? ? ? ? ? ? ? ??
如果使用if...else語(yǔ)句,那么這是一個(gè)很好節(jié)省代碼的方式。
Longhand:
const x = 20;let answer;if (x > 10) { answer = 'is greater'; } else { answer = 'is lesser'; }
Shorthand:
const answer = x > 10 ? 'is greater' : 'is lesser';
你還可以像下面這樣嵌套if語(yǔ)句:
const big = x > 10 ? " greater 10" : x
Short-circuit Evaluation ??
分配一個(gè)變量值到另一個(gè)變量的時(shí)候,你可能想要確保變量不是null、undefined或空。你可以寫(xiě)一個(gè)有多個(gè)if的條件語(yǔ)句或者Short-circuit Evaluation。
Longhand:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }
Shorthand:
const variable2 = variable1 || 'new';
不要相信我,請(qǐng)先相信自己的測(cè)試(可以把下面的代碼粘貼在es6console)
let variable1;let variable2 = variable1 || '';console.log(variable2 === ''); // prints truevariable1 = 'foo'; variable2 = variable1 || '';console.log(variable2); // prints foo
聲明變量 ? ? ? ? ? ? ? ? ? ? ??
在函數(shù)中聲明變量時(shí),像下面這樣同時(shí)聲明多個(gè)變量可以節(jié)省你大量的時(shí)間和空間:
Longhand:
let x;let y;let x = 3;
Shorthand:
let x, y, z=3;
如果存在 ? ? ? ? ? ? ? ? ? ? ?
這可能是微不足道的,但值得提及。做“如果檢查”時(shí),賦值操作符有時(shí)可以省略。
Longhand:
if (likeJavaScript === true)
Shorthand:
if (likeJavaScript)
注:這兩種方法并不完全相同,簡(jiǎn)寫(xiě)檢查只要likeJavaScript是true都將通過(guò)。
這有另一個(gè)示例。
如果a不是true,然后做什么。
Longhand:
let a;if ( a !== true ) {// do something...}
Shorthand:
let a;if ( !a ) {// do something...}
JavaScript的for循環(huán) ??
如果你只想要原生的JavaScript,而不想依賴(lài)于jQuery或Lodash這樣的外部庫(kù),那這個(gè)小技巧是非常有用的。
Longhand:
for (let i = 0; i < allImgs.length; i++)
Shorthand:
for (let index in allImgs)
Array.forEach簡(jiǎn)寫(xiě):
function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } [2, 5, 9].forEach(logArrayElements);// logs:// a[0] = 2// a[1] = 5// a[2] = 9
Short-circuit Evaluation ??
如果參數(shù)是null或者是undefined,我們可以簡(jiǎn)單的使用一個(gè)Short-circuit邏輯運(yùn)算,實(shí)現(xiàn)一行代碼替代六行代碼的寫(xiě)法。
Longhand:
let dbHost;if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; }
Shorthand:
const dbHost = process.env.DB_HOST || 'localhost';
十進(jìn)制指數(shù) ? ? ? ? ? ? ? ? ? ?
你可能看過(guò)這個(gè)。它本質(zhì)上是一個(gè)寫(xiě)數(shù)字的奇特寫(xiě)法,就是一個(gè)數(shù)字后面有很多個(gè)0。例如1e7本質(zhì)相當(dāng)于10000000(1的后面有7個(gè)0)。它代表了十進(jìn)制計(jì)數(shù)等于10000000。
Longhand:
for (let i = 0; i < 10000; i++) {}
Shorthand:
for (let i = 0; i < 1e7; i++) {} // All the below will evaluate to true1e0 === 1;1e1 === 10;1e2 === 100;1e3 === 1000;1e4 === 10000;1e5 === 100000;
對(duì)象屬性 ? ? ? ? ? ? ? ? ? ? ?
定義對(duì)象文字(Object literals)讓JavaScript變得更有趣。ES6提供了一個(gè)更簡(jiǎn)單的辦法來(lái)分配對(duì)象的屬性。如果屬性名和值一樣,你可以使用下面簡(jiǎn)寫(xiě)的方式。
Longhand:
const obj = { x:x, y:y };
Shorthand:
const obj = { x, y };
箭頭函數(shù) ? ? ? ? ? ? ? ? ? ? ?
經(jīng)典函數(shù)很容易讀和寫(xiě),但它們確實(shí)會(huì)變得有點(diǎn)冗長(zhǎng),特別是嵌套函數(shù)中調(diào)用其他函數(shù)時(shí)還會(huì)讓你感到困惑。
Longhand:
function sayHello(name) { console.log('Hello', name); } setTimeout(function() { console.log('Loaded') }, 2000); list.forEach(function(item) { console.log(item); });
Shorthand:
sayHello = name => console.log('Hello', name); setTimeout(() => console.log('Loaded'), 2000); list.forEach(item => console.log(item));
隱式返回 ? ? ? ? ? ? ? ? ? ?
return在函數(shù)中經(jīng)常使用到的一個(gè)關(guān)鍵詞,將返回函數(shù)的最終結(jié)果。箭頭函數(shù)用一個(gè)語(yǔ)句將隱式的返回結(jié)果(函數(shù)必須省略{},為了省略return關(guān)鍵詞)。
如果返回一個(gè)多行語(yǔ)句(比如對(duì)象),有必要在函數(shù)體內(nèi)使用()替代{}。這樣可以確保代碼是否作為一個(gè)單獨(dú)的語(yǔ)句返回。
Longhand:
function calcCircumference(diameter) { return Math.PI * diameter }
Shorthand:
calcCircumference = diameter => ( Math.PI * diameter; )
默認(rèn)參數(shù)值 ? ? ? ? ? ? ? ? ? ??
你可以使用if語(yǔ)句來(lái)定義函數(shù)參數(shù)的默認(rèn)值。在ES6中,可以在函數(shù)聲明中定義默認(rèn)值。
Longhand:
function volume(l, w, h) { if (w === undefined) w = 3; if (h === undefined) h = 4; return l * w * h; }
Shorthand:
volume = (l, w = 3, h = 4 ) => (l * w * h); volume(2) //output: 24
Template Literals ? ? ? ??
是不是厭倦了使用+來(lái)連接多個(gè)變量變成一個(gè)字符串?難道就沒(méi)有一個(gè)更容易的方法嗎?如果你能使用ES6,那么你是幸運(yùn)的。在ES6中,你要做的是使用撇號(hào)和${},并且把你的變量放在大括號(hào)內(nèi)。
Longhand:
const welcome = 'You have logged in as ' + first + ' ' + last + '.'const db = 'http://' + host + ':' + port + '/' + database;
Shorthand:
const welcome = `You have logged in as ${first} ${last}`;const db = `http://${host}:${port}/${database}`;
多行字符串 ? ? ? ? ? ? ? ?
你會(huì)發(fā)現(xiàn)以前自己寫(xiě)多行字符串的代碼會(huì)像下面這樣:
Longhand:
const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t' + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t' + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t' + 'veniam, quis nostrud exercitation ullamco laboris\n\t' + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t' + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'
但還有一個(gè)更簡(jiǎn)單的方法。使用撇號(hào)。
Shorthand:
const lorem = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.`
強(qiáng)制參數(shù) ? ? ? ? ? ? ? ?
默認(rèn)情況下,JavaScript如果不給函數(shù)參數(shù)傳一個(gè)值的話(huà),將會(huì)是一個(gè)undefined。有些語(yǔ)言也將拋出一個(gè)警告或錯(cuò)誤。在執(zhí)行參數(shù)賦值時(shí),你可以使用if語(yǔ)句,如果未定義將會(huì)拋出一個(gè)錯(cuò)誤,或者你可以使用強(qiáng)制參數(shù)(Mandatory parameter)。
Longhand:
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; }
Shorthand:
mandatory = () => { throw new Error('Missing parameter!'); }foo = (bar = mandatory()) => { return bar; }
Array.find ? ? ? ? ? ??
如果你以前寫(xiě)過(guò)一個(gè)查找函數(shù),你可能會(huì)使用一個(gè)for循環(huán)。在ES6中,你可以使用數(shù)組的一個(gè)新功能find()。
Longhand:
const pets = [ { type: 'Dog', name: 'Max'}, { type: 'Cat', name: 'Karl'}, { type: 'Dog', name: 'Tommy'}, ]function findDog(name) { for(let i = 0; i<pets.length; ++i) { if(pets[i].type === 'Dog' && pets[i].name === name) { return pets[i]; } } }
Shorthand:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');console.log(pet); // { type: 'Dog', name: 'Tommy' }
Object[key] ? ? ? ? ? ? ??
你知道Foo.bar也可以寫(xiě)成Foo[bar]吧。起初,似乎沒(méi)有理由應(yīng)該這樣寫(xiě)。然而,這個(gè)符號(hào)可以讓你編寫(xiě)可重用代碼塊。
下面是一段簡(jiǎn)化后的函數(shù)的例子:
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; }console.log(validate({first:'Bruce',last:'Wayne'})); // true
這個(gè)函數(shù)可以正常工作。然而,需要考慮一個(gè)這樣的場(chǎng)景:有很多種形式需要應(yīng)用驗(yàn)證,而且不同領(lǐng)域有不同規(guī)則。在運(yùn)行時(shí)很難創(chuàng)建一個(gè)通用的驗(yàn)證功能。
Shorthand:
// object validation rulesconst schema = { first: { required:true }, last: { required:true } }// universal validation functionconst validate = (schema, values) => { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true; }console.log(validate(schema, {first:'Bruce'})); // falseconsole.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
現(xiàn)在我們有一個(gè)驗(yàn)證函數(shù),可以各種形式的重用,而不需要為每個(gè)不同的功能定制一個(gè)驗(yàn)證函數(shù)。
Double Bitwise NOT ? ? ?
如果你是一位JavaScript新手的話(huà),對(duì)于逐位運(yùn)算符(Bitwise Operator)你應(yīng)該永遠(yuǎn)不會(huì)在任何地方使用。此外,如果你不處理二進(jìn)制0和1,那就更不會(huì)想使用。
然而,一個(gè)非常實(shí)用的用例,那就是雙位操作符。你可以用它替代Math.floor()。Double Bitwise NOT運(yùn)算符有很大的優(yōu)勢(shì),它執(zhí)行相同的操作要快得多。你可以在這里關(guān)于位運(yùn)算符相關(guān)的知識(shí)。
Longhand:
Math.floor(4.9) === 4 //true
Shorthand:
~~4.9 === 4 //true
?
總結(jié)
以上是生活随笔為你收集整理的15个JavaScript 编码小技巧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: $(function(){})和$(do
- 下一篇: 外省军人优待证到湖南省能免费看景区,坐地