總結分享20個提升效率的JavaScript簡寫技巧

WBOY
發布: 2022-01-13 18:11:20
轉載
1251 人瀏覽過

這篇文章為大家整理分享了20個提升效率的JavaScript簡寫技巧,希望對大家有幫助。

總結分享20個提升效率的JavaScript簡寫技巧

簡寫技巧

#當同時宣告多個變數時,可簡寫成一行

//Longhand
let x;
let y = 20;
 
//Shorthand
let x, y = 20;
登入後複製

利用解構,可為多個變數同時賦值

//Longhand
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];
登入後複製

巧用三元運算子簡化if else

//Longhand 
let marks = 26; 
let result; 
if (marks >= 30) {
   result = 'Pass'; 
} else { 
   result = 'Fail'; 
} 
//Shorthand 
let result = marks >= 30 ? 'Pass' : 'Fail';
登入後複製

使用||運算子給變數指定預設值

本質是利用了||運算子的特點,當前面的表達式的結果轉成布林值為false時,則值為後面表達式的結果

//Longhand
let imagePath;
let path = getImagePath();
if (path !== null && path !== undefined && path !== '') {
    imagePath = path;
} else {
    imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';
登入後複製

使用&&運算子簡化if語句

例如某個函數在某個條件為真時才調用,可簡寫

//Longhand
if (isLoggedin) {
    goToHomepage();
 }
//Shorthand
isLoggedin && goToHomepage();
登入後複製

使用解構交換兩個變數的值

let x = 'Hello', y = 55;
//Longhand
const temp = x;
x = y;
y = temp;
//Shorthand
[x, y] = [y, x];
登入後複製

適用箭頭函數簡化函數

//Longhand
function add(num1, num2) {
  return num1 + num2;
}
//Shorthand
const add = (num1, num2) => num1 + num2;
登入後複製

需要注意箭頭函數和普通函數的區別

使用字串模板簡化程式碼

使用模板字串代替原始的字串拼接

//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);
//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);
登入後複製

多行字串也可使用字串模板簡化

//Longhand
console.log('JavaScript, often abbreviated as JS, is a\n' + 
            'programming language that conforms to the \n' + 
            'ECMAScript specification. JavaScript is high-level,\n' + 
            'often just-in-time compiled, and multi-paradigm.'
            );
//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a
            programming language that conforms to the
            ECMAScript specification. JavaScript is high-level,
            often just-in-time compiled, and multi-paradigm.`
            );
登入後複製

對於多值匹配,可將所有值放在數組中,透過數組方法來簡寫

//Longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
  // Execute some code
}
// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
   // Execute some code
}
// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) { 
    // Execute some code 
}
登入後複製

巧用ES6對象的簡潔語法

例如,當屬性名稱和變數名稱相同時,可直接縮寫為一個

let firstname = 'Amitav';
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
登入後複製

使用一元運算子簡化字串轉數字

//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthand
let total = +'453';
let average = +'42.6';
登入後複製

使用repeat()方法簡化重複一個字串

//Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
  str += &#39;Hello &#39;;
}
console.log(str); // Hello Hello Hello Hello Hello
// Shorthand
&#39;Hello &#39;.repeat(5);
// 想跟你说100声抱歉!
&#39;sorry\n&#39;.repeat(100);
登入後複製

使用雙星號代替Math.pow()

//Longhand
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64
登入後複製

使用雙波線運算子(~~)取代Math.floor()

//Longhand
const floor = Math.floor(6.8); // 6
// Shorthand
const floor = ~~6.8; // 6
登入後複製

需要注意,~~僅適用於小於2147483647的數字

巧用擴充運算子(...)簡化程式碼

簡化數組合併

let arr1 = [20, 30];
//Longhand
let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]
//Shorthand
let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]
登入後複製

單層物件的拷貝

let obj = {x: 20, y: {z: 30}};
//Longhand
const makeDeepClone = (obj) => {
  let newObject = {};
  Object.keys(obj).map(key => {
      if(typeof obj[key] === &#39;object&#39;){
          newObject[key] = makeDeepClone(obj[key]);
      } else {
          newObject[key] = obj[key];
      }
});
return newObject;
}
const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
//Shorthand for single level object
let obj = {x: 20, y: &#39;hello&#39;};
const cloneObj = {...obj};
登入後複製

尋找陣列中的最大和最小值

// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2
登入後複製

使用for in和for of來簡化普通for迴圈

let arr = [10, 20, 30, 40];
//Longhand
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
//Shorthand
//for of loop
for (const val of arr) {
  console.log(val);
}
//for in loop
for (const index in arr) {
  console.log(arr[index]);
}
登入後複製

簡化取得字串中的某個字元

let str = &#39;jscurious.com&#39;;
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c
登入後複製

移除物件屬性

let obj = {x: 45, y: 72, z: 68, p: 98};
// Longhand
delete obj.x;
delete obj.p;
console.log(obj); // {y: 72, z: 68}
// Shorthand
let {x, p, ...newObj} = obj;
console.log(newObj); // {y: 72, z: 68}
登入後複製

使用arr.filter(Boolean)過濾掉陣列成員的值falsey

let arr = [12, null, 0, &#39;xyz&#39;, null, -25, NaN, &#39;&#39;, undefined, 0.5, false];
//Longhand
let filterArray = arr.filter(function(value) {
    if(value) return value;
});
// filterArray = [12, "xyz", -25, 0.5]
// Shorthand
let filterArray = arr.filter(Boolean);
// filterArray = [12, "xyz", -25, 0.5]
登入後複製

【相關推薦:javascript學習教程

以上是總結分享20個提升效率的JavaScript簡寫技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:juejin.im
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板