總結(jié)分享10 個超棒的 JavaScript 簡寫技巧
1.合并數(shù)組
普通寫法:
我們通常使用Array
中的concat()
方法合并兩個數(shù)組。用concat()
方法來合并兩個或多個數(shù)組,不會更改現(xiàn)有的數(shù)組,而是返回一個新的數(shù)組。請
看一個簡單的例子:
let apples = ['??', '??']; let fruits = ['??', '??', '??'].concat(apples); console.log( fruits ); //=> ["??", "??", "??", "??", "??"]
簡寫寫法:
我們可以通過使用ES6擴展運算符(...
)來減少代碼,如下所示:
let apples = ['??', '??']; let fruits = ['??', '??', '??', ...apples]; // <-- here console.log( fruits ); //=> ["??", "??", "??", "??", "??"]
2.合并數(shù)組(在開頭位置)
普通寫法: 假設(shè)我們想將apples
數(shù)組中的所有項添加到Fruits
數(shù)組的開頭,而不是像上一個示例中那樣放在末尾。我們可以使用Array.prototype.unshift()
來做到這一點:
let apples = ['??', '??']; let fruits = ['??', '??', '??']; // Add all items from apples onto fruits at start Array.prototype.unshift.apply(fruits, apples) console.log( fruits ); //=> ["??", "??", "??", "??", "??"]
簡寫寫法:
我們依然可以使用ES6擴展運算符(...
)縮短這段長代碼,如下所示:
let apples = ['??', '??']; let fruits = [...apples, '??', '??', '??']; // <-- here console.log( fruits ); //=> ["??", "??", "??", "??", "??"]
3.克隆數(shù)組
普通寫法:
我們可以使用Array
中的slice()
方法輕松克隆數(shù)組,如下所示:
let fruits = ['??', '??', '??', '??']; let cloneFruits = fruits.slice(); console.log( cloneFruits ); //=> ["??", "??", "??", "??"]
簡寫寫法:
我們可以使用ES6擴展運算符(...
)像這樣克隆一個數(shù)組:
let fruits = ['??', '??', '??', '??']; let cloneFruits = [...fruits]; // <-- here console.log( cloneFruits ); //=> ["??", "??", "??", "??"]
4.解構(gòu)賦值
普通寫法:
在處理數(shù)組時,我們有時需要將數(shù)組“解包”成一堆變量,如下所示:
let apples = ['??', '??']; let redApple = apples[0]; let greenApple = apples[1]; console.log( redApple ); //=> ?? console.log( greenApple ); //=> ??
簡寫寫法:
我們可以通過解構(gòu)賦值用一行代碼實現(xiàn)相同的結(jié)果:
let apples = ['??', '??']; let [redApple, greenApple] = apples; // <-- here console.log( redApple ); //=> ?? console.log( greenApple ); //=> ??
5.模板字面量
普通寫法:
通常,當我們必須向字符串添加表達式時,我們會這樣做:
// Display name in between two strings let name = 'Palash'; console.log('Hello, ' + name + '!'); //=> Hello, Palash! // Add & Subtract two numbers let num1 = 20; let num2 = 10; console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2)); //=> Sum = 30 and Subtract = 10
簡寫寫法:
通過模板字面量,我們可以使用反引號(``),這樣我們就可以將表達式包裝在
${…}`中,然后嵌入到字符串,如下所示:
// Display name in between two strings let name = 'Palash'; console.log(`Hello, ${name}!`); // <-- No need to use + var + anymore //=> Hello, Palash! // Add two numbers let num1 = 20; let num2 = 10; console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`); //=> Sum = 30 and Subtract = 10
6.For循環(huán)
普通寫法:
我們可以使用for
循環(huán)像這樣循環(huán)遍歷一個數(shù)組:
let fruits = ['??', '??', '??', '??']; // Loop through each fruit for (let index = 0; index < fruits.length; index++) { console.log( fruits[index] ); // <-- get the fruit at current index } //=> ?? //=> ?? //=> ?? //=> ??
簡寫寫法:
我們可以使用for...of
語句實現(xiàn)相同的結(jié)果,而代碼要少得多,如下所示:
let fruits = ['??', '??', '??', '??']; // Using for...of statement for (let fruit of fruits) { console.log( fruit ); } //=> ?? //=> ?? //=> ?? //=> ??
7.箭頭函數(shù)
普通寫法:
要遍歷數(shù)組,我們還可以使用Array
中的forEach()
方法。但是需要寫很多代碼,雖然比最常見的for
循環(huán)要少,但仍然比for...of
語句多一點:
let fruits = ['??', '??', '??', '??']; // Using forEach method fruits.forEach(function(fruit){ console.log( fruit ); }); //=> ?? //=> ?? //=> ?? //=> ??
簡寫寫法:
但是使用箭頭函數(shù)表達式,允許我們用一行編寫完整的循環(huán)代碼,如下所示:
let fruits = ['??', '??', '??', '??']; fruits.forEach(fruit => console.log( fruit )); // <-- Magic ? //=> ?? //=> ?? //=> ?? //=> ??
8.在數(shù)組中查找對象
普通寫法:
要通過其中一個屬性從對象數(shù)組中查找對象的話,我們通常使用for
循環(huán):
let inventory = [ {name: 'Bananas', quantity: 5}, {name: 'Apples', quantity: 10}, {name: 'Grapes', quantity: 2} ]; // Get the object with the name `Apples` inside the array function getApples(arr, value) { for (let index = 0; index < arr.length; index++) { // Check the value of this object property `name` is same as 'Apples' if (arr[index].name === 'Apples') { //=> ?? // A match was found, return this object return arr[index]; } } } let result = getApples(inventory); console.log( result ) //=> { name: "Apples", quantity: 10 }
簡寫寫法:
上面我們寫了這么多代碼來實現(xiàn)這個邏輯。但是使用Array
中的find()
方法和箭頭函數(shù)=>
,允許我們像這樣一行搞定:
// Get the object with the name `Apples` inside the array function getApples(arr, value) { return arr.find(obj => obj.name === 'Apples'); // <-- here } let result = getApples(inventory); console.log( result ) //=> { name: "Apples", quantity: 10 }
9.將字符串轉(zhuǎn)換為整數(shù)
普通寫法:
parseInt()
函數(shù)用于解析字符串并返回整數(shù):
let num = parseInt("10") console.log( num ) //=> 10 console.log( typeof num ) //=> "number"
簡寫寫法:
我們可以通過在字符串前添加+
前綴來實現(xiàn)相同的結(jié)果,如下所示:
let num = +"10"; console.log( num ) //=> 10 console.log( typeof num ) //=> "number" console.log( +"10" === 10 ) //=> true
10.短路求值
普通寫法:
如果我們必須根據(jù)另一個值來設(shè)置一個值不是falsy值,一般會使用if-else
語句,就像這樣:
function getUserRole(role) { let userRole; // If role is not falsy value // set `userRole` as passed `role` value if (role) { userRole = role; } else { // else set the `userRole` as USER userRole = 'USER'; } return userRole; } console.log( getUserRole() ) //=> "USER" console.log( getUserRole('ADMIN') ) //=> "ADMIN"
簡寫寫法:
但是使用短路求值(||
),我們可以用一行代碼執(zhí)行此操作,如下所示:
function getUserRole(role) { return role || 'USER'; // <-- here } console.log( getUserRole() ) //=> "USER" console.log( getUserRole('ADMIN') ) //=> "ADMIN"
補充幾點
箭頭函數(shù):
如果你不需要this
上下文,則在使用箭頭函數(shù)時代碼還可以更短:
let fruits = ['??', '??', '??', '??']; fruits.forEach(console.log);
在數(shù)組中查找對象:
你可以使用對象解構(gòu)和箭頭函數(shù)使代碼更精簡:
// Get the object with the name `Apples` inside the array const getApples = array => array.find(({ name }) => name === "Apples"); let result = getApples(inventory); console.log(result); //=> { name: "Apples", quantity: 10 }
短路求值替代方案:
const getUserRole1 = (role = "USER") => role; const getUserRole2 = role => role ?? "USER"; const getUserRole3 = role => role ? role : "USER";
編碼習慣
最后我想說下編碼習慣。代碼規(guī)范比比皆是,但是很少有人嚴格遵守。究其原因,多是在代碼規(guī)范制定之前,已經(jīng)有自己的一套代碼習慣,很難短時間改變自己的習慣。良好的編碼習慣可以為后續(xù)的成長打好基礎(chǔ)。下面,列舉一下開發(fā)規(guī)范的幾點好處,讓大家明白代碼規(guī)范的重要性:
- 規(guī)范的代碼可以促進團隊合作。
- 規(guī)范的代碼可以減少 Bug 處理。
- 規(guī)范的代碼可以降低維護成本。
- 規(guī)范的代碼有助于代碼審查。
- 養(yǎng)成代碼規(guī)范的習慣,有助于程序員自身的成長。
到此這篇關(guān)于總結(jié)分享10 個超棒的 JavaScript 簡寫技巧的文章就介紹到這了,更多相關(guān)JS簡寫技巧內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript統(tǒng)計數(shù)組中相同的數(shù)量的方法總結(jié)
在JavaScript中,我們經(jīng)常需要對數(shù)組中對象的屬性進行統(tǒng)計。在本文中,我們將介紹如何使用JavaScript來實現(xiàn)這一功能,文中有詳細的代碼示例,需要的朋友可以借鑒參考2023-05-05BOOTSTRAP時間控件顯示在模態(tài)框下面的bug修復(fù)
這篇文章主要介紹了BOOTSTRAP時間控件顯示在模態(tài)框下面的bug修復(fù),需要的朋友可以參考下2015-02-02JS實現(xiàn)不使用圖片仿Windows右鍵菜單效果代碼
這篇文章主要介紹了JS實現(xiàn)不使用圖片仿Windows右鍵菜單效果代碼,涉及文鼎字及css樣式的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10d3.js實現(xiàn)簡單的網(wǎng)絡(luò)拓撲圖實例代碼
最近一直在學(xué)習d3.js,大家都知道d3.js是一個非常不錯的數(shù)據(jù)可視化庫,我們可以用它來做一些比較酷的東西,比如可以來顯示一些簡單的網(wǎng)絡(luò)拓撲圖,這篇文中就通過實例代碼給大家介紹了如何利用d3.js實現(xiàn)簡單的網(wǎng)絡(luò)拓撲圖,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-11-11JavaScript中apply方法的應(yīng)用技巧小結(jié)
這篇文章給大家總結(jié)了在js中apply方法的一些應(yīng)用技巧,通過這些技巧對大家日常的使用相信會有幫助,有需要的朋友們下面來一起看看吧。2016-09-09