日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

15个JavaScript 编码小技巧

發布時間:2024/9/19 javascript 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 15个JavaScript 编码小技巧 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

三元操作符 ? ? ? ? ? ? ? ? ? ??

如果使用if...else語句,那么這是一個很好節省代碼的方式。

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語句:

const big = x > 10 ? " greater 10" : x

Short-circuit Evaluation ??

分配一個變量值到另一個變量的時候,你可能想要確保變量不是null、undefined或空。你可以寫一個有多個if的條件語句或者Short-circuit Evaluation。

Longhand:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }

Shorthand:

const variable2 = variable1 || 'new';

不要相信我,請先相信自己的測試(可以把下面的代碼粘貼在es6console)

let variable1;let variable2 = variable1 || '';console.log(variable2 === ''); // prints truevariable1 = 'foo'; variable2 = variable1 || '';console.log(variable2); // prints foo

聲明變量 ? ? ? ? ? ? ? ? ? ? ??

在函數中聲明變量時,像下面這樣同時聲明多個變量可以節省你大量的時間和空間:

Longhand:

let x;let y;let x = 3;

Shorthand:

let x, y, z=3;

如果存在 ? ? ? ? ? ? ? ? ? ? ?

這可能是微不足道的,但值得提及。做“如果檢查”時,賦值操作符有時可以省略。

Longhand:

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

注:這兩種方法并不完全相同,簡寫檢查只要likeJavaScript是true都將通過。

這有另一個示例。

如果a不是true,然后做什么。

Longhand:

let a;if ( a !== true ) {// do something...}

Shorthand:

let a;if ( !a ) {// do something...}

JavaScript的for循環 ??

如果你只想要原生的JavaScript,而不想依賴于jQuery或Lodash這樣的外部庫,那這個小技巧是非常有用的。

Longhand:

for (let i = 0; i < allImgs.length; i++)

Shorthand:

for (let index in allImgs)

Array.forEach簡寫:

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 ??

如果參數是null或者是undefined,我們可以簡單的使用一個Short-circuit邏輯運算,實現一行代碼替代六行代碼的寫法。

Longhand:

let dbHost;if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; }

Shorthand:

const dbHost = process.env.DB_HOST || 'localhost';

十進制指數 ? ? ? ? ? ? ? ? ? ?

你可能看過這個。它本質上是一個寫數字的奇特寫法,就是一個數字后面有很多個0。例如1e7本質相當于10000000(1的后面有7個0)。它代表了十進制計數等于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;

對象屬性 ? ? ? ? ? ? ? ? ? ? ?

定義對象文字(Object literals)讓JavaScript變得更有趣。ES6提供了一個更簡單的辦法來分配對象的屬性。如果屬性名和值一樣,你可以使用下面簡寫的方式。

Longhand:

const obj = { x:x, y:y };

Shorthand:

const obj = { x, y };

箭頭函數 ? ? ? ? ? ? ? ? ? ? ?

經典函數很容易讀和寫,但它們確實會變得有點冗長,特別是嵌套函數中調用其他函數時還會讓你感到困惑。

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在函數中經常使用到的一個關鍵詞,將返回函數的最終結果。箭頭函數用一個語句將隱式的返回結果(函數必須省略{},為了省略return關鍵詞)。

如果返回一個多行語句(比如對象),有必要在函數體內使用()替代{}。這樣可以確保代碼是否作為一個單獨的語句返回。

Longhand:

function calcCircumference(diameter) { return Math.PI * diameter }

Shorthand:

calcCircumference = diameter => ( Math.PI * diameter; )

默認參數值 ? ? ? ? ? ? ? ? ? ??

你可以使用if語句來定義函數參數的默認值。在ES6中,可以在函數聲明中定義默認值。

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 ? ? ? ??

是不是厭倦了使用+來連接多個變量變成一個字符串?難道就沒有一個更容易的方法嗎?如果你能使用ES6,那么你是幸運的。在ES6中,你要做的是使用撇號和${},并且把你的變量放在大括號內。

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}`;

多行字符串 ? ? ? ? ? ? ? ?

你會發現以前自己寫多行字符串的代碼會像下面這樣:

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'

但還有一個更簡單的方法。使用撇號。

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.`

強制參數 ? ? ? ? ? ? ? ?

默認情況下,JavaScript如果不給函數參數傳一個值的話,將會是一個undefined。有些語言也將拋出一個警告或錯誤。在執行參數賦值時,你可以使用if語句,如果未定義將會拋出一個錯誤,或者你可以使用強制參數(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 ? ? ? ? ? ??

如果你以前寫過一個查找函數,你可能會使用一個for循環。在ES6中,你可以使用數組的一個新功能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也可以寫成Foo[bar]吧。起初,似乎沒有理由應該這樣寫。然而,這個符號可以讓你編寫可重用代碼塊。

下面是一段簡化后的函數的例子:

function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; }console.log(validate({first:'Bruce',last:'Wayne'})); // true

這個函數可以正常工作。然而,需要考慮一個這樣的場景:有很多種形式需要應用驗證,而且不同領域有不同規則。在運行時很難創建一個通用的驗證功能。

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

現在我們有一個驗證函數,可以各種形式的重用,而不需要為每個不同的功能定制一個驗證函數。

Double Bitwise NOT ? ? ?

如果你是一位JavaScript新手的話,對于逐位運算符(Bitwise Operator)你應該永遠不會在任何地方使用。此外,如果你不處理二進制0和1,那就更不會想使用。

然而,一個非常實用的用例,那就是雙位操作符。你可以用它替代Math.floor()。Double Bitwise NOT運算符有很大的優勢,它執行相同的操作要快得多。你可以在這里關于位運算符相關的知識。

Longhand:

Math.floor(4.9) === 4 //true

Shorthand:

~~4.9 === 4 //true

?

總結

以上是生活随笔為你收集整理的15个JavaScript 编码小技巧的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。