每一位程序員不想讓自己的代碼寫的特別冗余,能用一行解決的事情堅決不寫兩行。今天給大家分享幾個常見的簡寫方式
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、 字符串轉成數字
有一些內置的方法,例如parseInt和parseFloat可以用來將字符串轉為數字。我們還可以簡單地在字符串前提供一個一元運算符 (+) 來實現這一點。
//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
以上是常見的一些簡寫技巧,留着備用參考
