開發者的生活老是在學習新的東西,跟上變化不該該比如今更難,個人動機是介紹全部JavaScript的最佳實踐,好比簡寫功能,做爲一個前端開發者,咱們必須知道,讓咱們的生活在2021年變得更輕鬆。前端
你可能作了很長時間的JavaScript開發,但有時你可能沒有更新最新的特性,這些特性能夠解決你的問題,而不須要作或編寫一些額外的代碼。這些技術能夠幫助您編寫乾淨和優化的JavaScript代碼。此外,這些主題能夠幫助你爲2021年的JavaScript面試作準備。面試
咱們能夠在數組中存儲多個值,而且可使用數組 include
方法。編程
//Longhand if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') { //logic } //Shorthand if (['abc', 'def', 'ghi', 'jkl'].includes(x)) { //logic }
這對於咱們有 if-else
條件,裏面不包含更大的邏輯時,是一個較大的捷徑。咱們能夠簡單的使用三元運算符來實現這個簡寫。數組
// Longhand let test: boolean; if (x > 100) { test = true; } else { test = false; } // Shorthand let test = (x > 10) ? true : false; //or we can use directly let test = x > 10; console.log(test);
當咱們有嵌套條件時,咱們能夠採用這種方式。less
let x = 300, test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100'; console.log(test2); // "greater than 100"
當咱們要聲明兩個具備共同值或共同類型的變量時,可使用此簡寫形式。函數
//Longhand let test1; let test2 = 1; //Shorthand let test1, test2 = 1;
當咱們建立新的變量時,有時咱們想檢查咱們引用的變量的值是否爲空或undefined。JavaScript確實有一個很是好的簡寫工具來實現這些功能。工具
// Longhand if (test1 !== null || test1 !== undefined || test1 !== '') { let test2 = test1; } // Shorthand let test2 = test1 || '';
let test1 = null, test2 = test1 || ''; console.log("null check", test2); // output will be ""
let test1 = undefined, test2 = test1 || ''; console.log("undefined check", test2); // output will be ""
正常值檢查學習
let test1 = 'test', test2 = test1 || ''; console.log(test2); // output: 'test'
當咱們處理多個變量並但願將不一樣的值分配給不一樣的變量時,此簡寫技術很是有用。優化
//Longhand let test1, test2, test3; test1 = 1; test2 = 2; test3 = 3; //Shorthand let [test1, test2, test3] = [1, 2, 3];
咱們在編程中處理不少算術運算符,這是將運算符分配給JavaScript變量的有用技術之一。this
// Longhand test1 = test1 + 1; test2 = test2 - 1; test3 = test3 * 20; // Shorthand test1++; test2--; test3 *= 20;
這是咱們你們都在使用的經常使用簡寫之一,但仍然值得一提。
// Longhand if (test1 === true) or if (test1 !== "") or if (test1 !== null) // Shorthand //it will check empty string,null and undefined too if (test1)
注意:若是test1有任何值,它將在if循環後進入邏輯,該運算符主要用於 null
或 undefined
的檢查。
若是僅在變量爲 true
的狀況下才調用函數,則可使用 &&
運算符。
//Longhand if (test1) { callMethod(); } //Shorthand test1 && callMethod();
這是迭代的經常使用簡寫技術之一。
// Longhand for (var i = 0; i < testData.length; i++) // Shorthand for (let i in testData) or for (let i of testData)
每一個變量的數組
function testData(element, index, array) { console.log('test[' + index + '] = ' + element); } [11, 24, 32].forEach(testData); // logs: test[0] = 11, test[1] = 24, test[2] = 32
咱們也能夠在return語句中使用比較。它將避免咱們的5行代碼,並將它們減小到1行。
// Longhand let test; function checkReturn() { if (!(test === undefined)) { return test; } else { return callMe('test'); } } var data = checkReturn(); console.log(data); //output test function callMe(val) { console.log(val); } // Shorthand function checkReturn() { return test || callMe('test'); }
//Longhand function add(a, b) { return a + b; } //Shorthand const add = (a, b) => a + b;
更多示例。
function callMe(name) { console.log('Hello', name); } callMe = name => console.log('Hello', name);
咱們可使用三元運算符來實現這些功能。
// Longhand function test1() { console.log('test1'); }; function test2() { console.log('test2'); }; var test3 = 1; if (test3 == 1) { test1(); } else { test2(); } // Shorthand (test3 === 1? test1:test2)();
咱們能夠將條件保存在鍵值對象中,並能夠根據條件使用。
// Longhand switch (data) { case 1: test1(); break; case 2: test2(); break; case 3: test(); break; // And so on... } // Shorthand var data = { 1: test1, 2: test2, 3: test }; data[something] && data[something]();
使用箭頭函數,咱們能夠直接返回值,而沒必要編寫return語句。
//longhand function calculate(diameter) { return Math.PI * diameter } //shorthand calculate = diameter => ( Math.PI * diameter; )
// Longhand for (var i = 0; i < 10000; i++) { ... } // Shorthand for (var i = 0; i < 1e4; i++) {
//Longhand function add(test1, test2) { if (test1 === undefined) test1 = 1; if (test2 === undefined) test2 = 2; return test1 + test2; } //shorthand add = (test1 = 1, test2 = 2) => (test1 + test2); add() //output: 3
//longhand // joining arrays using concat const data = [1, 2, 3]; const test = [4 ,5 , 6].concat(data); //shorthand // joining arrays const data = [1, 2, 3]; const test = [4 ,5 , 6, ...data]; console.log(test); // [ 4, 5, 6, 1, 2, 3]
對於克隆,咱們也可使用擴展運算符。
//longhand // cloning arrays const test1 = [1, 2, 3]; const test2 = test1.slice() //shorthand // cloning arrays const test1 = [1, 2, 3]; const test2 = [...test1];
若是您厭倦了在單個字符串中使用 +
來鏈接多個變量,那麼這種簡寫能夠消除您的頭痛。
//longhand const welcome = 'Hi ' + test1 + ' ' + test2 + '.' //shorthand const welcome = `Hi ${test1} ${test2}`;
當咱們在代碼中處理多行字符串時,可使用如下功能:
//longhand const data = 'abc abc abc abc abc abc\n\t' + 'test test,test test test test\n\t' //shorthand const data = `abc abc abc abc abc abc test test,test test test test`
let test1 = 'a'; let test2 = 'b'; //Longhand let obj = {test1: test1, test2: test2}; //Shorthand let obj = {test1, test2};
//Longhand let test1 = parseInt('123'); let test2 = parseFloat('12.3'); //Shorthand let test1 = +'123'; let test2 = +'12.3';
//longhand const test1 = this.data.test1; const test2 = this.data.test2; const test2 = this.data.test3; //shorthand const { test1, test2, test3 } = this.data;
當咱們確實有一個對象數組而且咱們想要根據對象屬性查找特定對象時,find方法確實頗有用。
const data = [ { type: 'test1', name: 'abc' }, { type: 'test2', name: 'cde' }, { type: 'test1', name: 'fgh' }, ] function findtest1(name) { for (let i = 0; i < data.length; ++i) { if (data[i].type === 'test1' && data[i].name === name) { return data[i]; } } } //Shorthand filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh'); console.log(filteredData); // { type: 'test1', name: 'fgh' }
若是咱們有代碼來檢查類型,根據類型須要調用不一樣的方法,咱們能夠選擇使用多個else ifs或者switch,可是若是咱們有比這更好的簡寫方法呢?
// Longhand if (type === 'test1') { test1(); } else if (type === 'test2') { test2(); } else if (type === 'test3') { test3(); } else if (type === 'test4') { test4(); } else { throw new Error('Invalid value ' + type); } // Shorthand var types = { test1: test1, test2: test2, test3: test3, test4: test4 }; var func = types[type]; (!func) && throw new Error('Invalid value ' + type); func();
當咱們遍歷數組以查找特定值時,咱們確實使用 indexOf()
方法,若是找到更好的方法該怎麼辦?讓咱們看看這個例子。
//longhand if(arr.indexOf(item) > -1) { // item found } if(arr.indexOf(item) === -1) { // item not found } //shorthand if(~arr.indexOf(item)) { // item found } if(!~arr.indexOf(item)) { // item not found }
按位(〜
)運算符將返回除-1之外的任何值的真實值。否認它就像作 ~~
同樣簡單。另外,咱們也可使用 include()
函數:
if (arr.includes(item)) { // true if the item found }
此函數有助於將對象轉換爲對象數組。
const data = { test1: 'abc', test2: 'cde', test3: 'efg' }; const arr = Object.entries(data); console.log(arr); /** Output: [ [ 'test1', 'abc' ], [ 'test2', 'cde' ], [ 'test3', 'efg' ] ] **/
這也是ES8中引入的一項新功能,該功能執行與 Object.entries()
相似的功能,但沒有關鍵部分:
const data = { test1: 'abc', test2: 'cde' }; const arr = Object.values(data); console.log(arr); /** Output: [ 'abc', 'cde'] **/
雙重NOT按位運算符方法僅適用於32位整數)
// Longhand Math.floor(1.9) === 1 // true // Shorthand ~~1.9 === 1 // true
要一次又一次地重複相同的字符,咱們可使用for循環並將它們添加到同一循環中,可是若是咱們有一個簡寫方法呢?
//longhand let test = ''; for(let i = 0; i < 5; i ++) { test += 'test '; } console.log(str); // test test test test test //shorthand 'test '.repeat(5);
const arr = [1, 2, 3]; Math.max(…arr); // 3 Math.min(…arr); // 1
let str = 'abc'; //Longhand str.charAt(2); // c //Shorthand Note: If we know the index of the array then we can directly use index insted of character.If we are not sure about index it can throw undefined str[2]; // c
//longhand Math.pow(2,3); // 8 //shorthand 2**3 // 8