當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
一些JS优化小技巧
1. if多條件判斷
如果if里面包含多個判斷條件,可以把判斷條件存到一個數組,然后在去這個數組中檢索”輸入的值“是否滿足條件;
// 冗余 if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {}// 簡潔 if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {}2. if…else…
單個if else可以直接使用變量賦值替代,省時省力
// 冗余 let test: boolean; if (x > 100) {test = true; } else {test = false; }// 簡潔 let test = x > 10;3. Null, Undefined, 空值檢查
空值檢查的時候,一般會寫很多個判空處理,這樣子過于榮譽。使用 || 運算符,從左到右,如果為真則直接賦值,直到所有的都不為真,則返回假;
// 冗余 if (first !== null || first !== undefined || first !== '') {let second = first; }// 簡潔 let second = first || '';4. foreach循環
foreach循環代碼過于冗余,可以使用 for in 或者for of代替;
// 冗余 for (var i = 0; i < testData.length; i++)// 簡潔 for (let i in testData) // 或 for (let i of testData)5. 函數條件調用
如果需要根據條件判斷,執行不同的函數。
// 冗余 function test1() {console.log('test1'); }; function test2() {console.log('test2'); }; var test3 = 1; if (test3 == 1) {test1(); } else {test2(); }// 簡單 (test3 === 1? test1:test2)();使用三目運算符進行判斷,然后在讓函數自己執行;
6. switch條件
如果需要根據條件判斷,執行不同的函數,并且此時判斷的條件比較多的時候;可以使用,將條件進行數組存儲,然后在判斷數組中是否存在”該條件“進行,函數執行處理;
// 冗余 switch (data) {case 1:test1();break;case 2:test2();break;case 3:test();break;// so on... }// 簡潔 var data = {1: test1,2: test2,3: test };data[anything] && data[anything]();7. 多行字符串
如果有多行字符串,就不要使用字符串拼接了,不美觀,又不好維護。使用,模板字符串。
// 冗余 const data = 'abc abc abc abc abc abc\n\t'+ 'test test,test test test test\n\t'// 簡潔 const data = `abc abc abc abc abc abctest test,test test test test`8. 隱式返回
如果返回只有一行代碼,可以使用箭頭函數代替普通函數,并且不用再寫 return
// 冗余 function getArea(diameter) {return Math.PI * diameter }// 簡潔 getArea = diameter => (Math.PI * diameter; )9. 冪乘
某個數的幾次方,一般使用Math.pow(),也可以使用**直接次方。
// 冗余 Math.pow(2,3);// 簡潔而 2**3 // 8總結
- 上一篇: 动态高度过渡动画
- 下一篇: 商品图片放大镜的JavaScript实现