分享幾個驚艷的JavaScript 代碼技巧!
多表達式多if判斷
我們可以在數組中存儲多個值,并且可以使用數組include方法。
// 長
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
?//logic
}
// 短
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
?//logic
}
簡寫 if else
如果 if-else 的邏輯比較簡單,可以使用下面這種方式鏡像簡寫,當然也可以使用三元運算符來實現(xiàn)。
// 長
let test: boolean;
if (x > 100) {
?test = true;
} else {
?test = false;
}
// 短
let test = (x > 10) ? true : false;
// 也可以直接這樣
let test = x > 10;
合并變量聲明
當我們聲明多個同類型的變量時,可以像下面這樣簡寫。
// 長
let test1;
let test2 = 1;
// 短
let test1, test2 = 1;
合并變量賦值
當我們處理多個變量并將不同的值分配給不同的變量時,這種方式非常有用。
// 長
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
// 短
let [test1, test2, test3] = [1, 2, 3];
&& 運算符
如果僅在變量值為 true 的情況下才調用函數,則可以使用 && 運算符。
// 長
if (test1) {
callMethod();
}
// 短
test1 && callMethod();
箭頭函數
// 長 ?
function add(a, b) {
? return a + b;
}
// 短
const add = (a, b) => a + b;
短函數調用
可以使用三元運算符來實現(xiàn)這些功能。
const fun1 = () => console.log('fun1');
const fun2 = () => console.log('fun2');
// 長
let test = 1;
if (test == 1) {
?fun1();
} else{
?fun2();
}
// 短
(test === 1? fun1:fun2)();
默認參數值
// 長
function add(test1, test2) {
?if (test1 === undefined)
? ?test1 = 1;
?if (test2 === undefined)
? ?test2 = 2;
?return test1 + test2;
}
// 短
const add = (test1 = 1, test2 = 2) => (test1 + test2);
擴展運算符
// 長-合并數組
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
// 短-合并數組
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
// 長-拷貝數組
const test1 = [1, 2, 3];
const test2 = test1.slice()
// 短-拷貝數組
const test1 = [1, 2, 3];
const test2 = [...test1];