JS中一些常見的簡寫方式


每一位程序員不想讓自己的代碼寫的特別冗余,能用一行解決的事情堅決不寫兩行。今天給大家分享幾個常見的簡寫方式

1、變量的聲明

//Longhand
let x;
let y = 20;
//Shorthand
let x, y = 20;

2、給多個變量賦值

//Longhand
let a, b, c;
a = 5;
b = 8;
c = 12;

//Shorthand
let [a, b, c] = [5, 8, 12];

3、賦默認的值

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

4、與 (&&) 短路運算

如果你只有當某個變量為 true 時調用一個函數,那么你可以使用與 (&&)短路形式書寫。

//Longhand
if (isLoggedin) {
 goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();

5、在多個條件中查找是否存在條件 ,我們可以將所有的值放到數組中,然后使用indexOf()includes()方法。

/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
}

6、 字符串轉成數字

有一些內置的方法,例如parseIntparseFloat可以用來將字符串轉為數字。我們還可以簡單地在字符串前提供一個一元運算符 (+) 來實現這一點。

//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthand
let total = +'453';
let average = +'42.6';

7、找出數組中的最大和最小數字

// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2

以上是常見的一些簡寫技巧,留着備用參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM