都说不会“懒惰”的工程师不是一个好程序员,今天分享一下,这几年来代码优化总结
1. 多个if条件判断
NORMAL:
if (x === 'Tom' || x === 'Jerry' || x === 'Daniel' || x ==='Jack') {}
BETTER:
if (['Tom', 'Jerry', 'Daniel', 'Jack'].includes(x)) {}
2. if…else…
NORMAL:
let isOverTen: boolean;
if (x > 10) {
isOverTen = true;
} else {
isOverTen = false;
}
BETTER:
let isOverTen = x > 10;
3. 检查 value 是否是 Null, Undefined, null
NORMAL:
let second = '';
if (first !== null || first !== undefined || first !== '') {
second = first;
}
BETTER:
let second = first || '';
4. For 循环
NORMAL:
for (var i = 0; i < testData.length; i++)
BETTER:
for (let i in testData)
// or
for (let i of testData)
5. Function 条件调用
NORMAL:
function method1() {
console.log('call method1');
};
function method2() {
console.log('call method2');
};
let text = 1;
if (text == 1) {
method1();
} else {
method2();
}
BETTER:
(text === 1? method1:method2)();
6. switch 表达式
NORMAL:
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// so on...
}
BETTER:
var data = {
1: test1,
2: test2,
3: test
};
data[case] && data[case]();
7. 多行 String
NORMAL:
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t'
BETTER:
const data = `abc abc abc abc abc abc
test test,test test test test`
8. 隐式返回
NORMAL:
function getArea(diameter) {
return Math.PI * diameter
}
BETTER:
const getArea = diameter => Math.PI * diameter;
9. 迭代重复
NORMAL:
let text = '';
for(let i = 0; i < 5; i ++) {
text += 'text ';
}
BETTER:
'text '.repeat(5);
10. 幂运算
NORMAL:
Math.pow(2,3);
BETTER:
2**3 // 8
11. Foreach 循环
NORMAL:
const array1 = ['a', 'b', 'c'];
array1.forEach(function (element){
console.log(element)
});
BETTER:
const array1 = ['a', 'b', 'c'];
for (let element in array1){
console.log(element)
}