分享一些常用代码优化技巧,希望对你有所帮助。
1.利用include缩短条件语句判断
const x = 'a';
//常规写法
if (x === 'a' || x === 'b' || x === 'c' || x === 'd') {
//logic
}
//简化写法
if (['a', 'b', 'c', 'd'].includes(x)) {
//logic
}
2.利用三目运算符简化条件判断语句
//常规写法
let isBig: boolean;
const y= 100;
if (y > 10) {
isBig = true;
} else {
isBig = false;
}
//简化写法
let isBig1 = (y > 10) ? true : false;
//极简写法
let isBig2 = y > 10;
3.变量声明合并
//分开写变量
let test1 = 1;
let text2 = 2;
//合并写法
let text3 = 1, text4 = 2;
4.&& 运算符的合理使用
//常见写法
if (test1) {
callMethod();
}
//如果仅在变量值为 true 的情况下才调用函数,则可以使用 && 运算符。
test1 && callMethod();
5.箭头函数的合理使用
//常规函数
function add1(a, b) {
return a + b;
}
//箭头函数
const add2 = (a, b) => a + b;
6.默认参数的合理使用
//在函数内部做是否为空的判断
function add1(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;
}
//直接给默认值,减少代码量
const add2 = (test1 = 1, test2 = 2) => (test1 + test2);
7.扩展运算符的使用
//利用合并函数合并
const data1 = [1, 2, 3];
const test1 = [4 ,5 , 6].concat(data1);
//利用扩展运算符合并
const data2 = [1, 2, 3];
const test2 = [4 ,5 , 6, ...data2];
//利用拷贝函数拷贝数组
const test3 = [1, 2, 3];
const test4 = test1.slice()
//利用扩展运算符拷贝数组
const test5 = [1, 2, 3];
const test6 = [...test1];
8.拼接字符串技巧
const test1 = 'Mark';
const test2 = 'want are you doing lately';
//原始的拼接
const welcome1 = 'Hi ' + test1 + ' ' + test2 + '?'
//利用模板字符串拼接
const welcome2 = `Hi ${test1} ${test2}?`;
9.在数组中查找最大值和最小值
const arr = [1, 2, 3];
const max = Math.max(...arr);
const min = Math.min(...arr);
10.Switch简单的写法
const data = 1;
const test = () => {
console.log('test function');
};
const test1 = () => {
console.log('test1 function');
};
const test2 = () => {
console.log('test2 function');
};
//switch条件判断
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
//键值对条件判断
const data2 = {
1: test1,
2: test2,
3: test,
};
data2[1] && data2[1]();
11.快速获取数组最后一个元素的方法
const array1 = [
'this is the first element',
'this is the second element',
'this is the last element',
];
//利用length来访问数组末尾元素
console.log(array1[array1.length - 1]); // logs 'this is the last element'
//利用at()函数来获取最后元素
console.log(array1.at(0)); // logs 'this is the first element'
console.log(array1.at(-2)); // logs 'this is the second element'
console.log(array1.at(-1)); // logs 'this is the last element'