分享一些我常用的代码优化技巧
1. 多表达式多 if 判断
我们可以在数组中存储多个值,并且可以使用数组include方法。
// 长if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {//logic}// 短if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {//logic}
2. 简写 if else
如果 if-else 的逻辑比较降低,可以使用下面这种方式镜像简写,当然也可以使用三元运算符来实现。
// 长let test: boolean;if (x > 100) {test = true;} else {test = false;}// 短let test = (x > 10) ? true : false;// 也可以直接这样let test = x > 10;
3. 合并变量声明
当我们声明多个同类型的变量时,可以像下面这样简写。
// 长let test1;let test2 = 1;// 短let test1, test2 = 1;
4. 合并变量赋值
当我们处理多个变量并将不同的值分配给不同的变量时,这种方式非常有用。
// 长let test1, test2, test3;test1 = 1;test2 = 2;test3 = 3;// 短let [test1, test2, test3] = [1, 2, 3];
5. && 运算符
如果仅在变量值为 true 的情况下才调用函数,则可以使用 && 运算符。
// 长if (test1) {callMethod();}// 短test1 && callMethod();
6. 箭头函数
// 长function add(a, b) {return a + b;}// 短const add = (a, b) => a + b;
7. 短函数调用
可以使用三元运算符来实现这些功能。
const fun1 = () => console.log('fun1');const fun2 = () => console.log('fun2');// 长let test = 1;if (test == 1) {fun1();} else{fun2();}// 短(test === 1? fun1:fun2)();
8. Switch 简记法
我们可以将条件保存在键值对象中,并可以根据条件使用。
// 长switch (data) {case 1:test1();break;case 2:test2();break;case 3:test();break;// And so on...}// 短const data = {1: test1,2: test2,3: test};data[something] && data[something]();
9. 默认参数值
// 长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);
10. 扩展运算符
// 长-合并数组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];
11. 模版字符串
// 长const welcome = 'Hi ' + test1 + ' ' + test2 + '.'// 短const welcome = `Hi ${test1} ${test2}`;
12. 简写对象
let test1 = 'a';let test2 = 'b';// 长let obj = {test1: test1, test2: test2};// 短let obj = {test1, test2};
13. 在数组中查找最大值和最小值
const arr = [1, 2, 3];Math.max(…arr); // 3Math.min(…arr); // 1
14. For循环简写
如果您想要纯JavaScript并且不想依赖外部库(如jQuery或lodash),这个小技巧非常有用。
常规:
var array = [1,2,3,4,5,6,7];
for (var i = 0; i < array.length; i) {
console.log(i,array[i]);
}
简写:
1、用for in的方遍历数组
for(let index in array) {
console.log(index,array[index]);
};
2、用forEach
array.forEach(v=>{
console.log(v);
});
array.forEach(function(v){
console.log(v);
});
3、for in 用for in不仅可以对数组,也可以对enumerable对象操作
var A = {a:1,b:2,c:3,d:"hello world"};
for(let k in A) {
console.log(k,A[k]);
}
4、在ES6中,增加了一个for of循环,使用起来很简单
for(let v of array) {
console.log(v); // 输出val值
};
本文分享了14种实用的代码优化技巧,包括使用数组`includes`替代多条件`if`,简写`if-else`,合并变量声明和赋值,利用`&&`运算符,箭头函数,短函数调用,`switch`简记法,扩展运算符,模板字符串,简写对象,快速找数组最大值和最小值,以及`for`循环简写方法。通过这些技巧,可以提高代码的可读性和执行效率。
138

被折叠的 条评论
为什么被折叠?



