文章目录
- 18 个JS优化技巧,可以解决 90% 的屎山代码!!!
- 1.箭头函数
- 2.解构赋值变量
- 3.使用模版字面量进行字符拼接
- 4.使用展开运算符进行数组和对象操作
- 5.简化循环
- 6.简化判断
- 7.使用对象解构和默认参数简化函数参数
- 8.使用函数式编程概念如纯函数和函数组合
- 9.使用对象字面量简化对象的创建和定义
- 10.使用适当的命名和注释来提高代码可读性
- 11.条件判断优化
- if else
- switch case
- 判断封装
- Object.assign给默认对象赋默认值
- 函数参数“两个”以下最好
- 12.使用解释形语言
- 13.让对象拥有私有成员-通过闭包来实现
参考:https://blog.csdn.net/techforward/article/details/131961841
18 个JS优化技巧,可以解决 90% 的屎山代码!!!
1.箭头函数
// 传统函数定义
function add(a, b) {return a + b;
}
// 箭头函数简化
const add = (a, b) => a + b;
2.解构赋值变量
// 获取对象中的指定属性值
const firstName = person.firstName;
const lastName = person.lastName;// 直接赋值对象,指定属性赋值
const { firstName, lastName } = person;console.log(fistName)
console.log(lastName)
3.使用模版字面量进行字符拼接
// 传统字符串拼接
const val = 'Hello ' + name + '!';
// 模板字面量简化
const val = `Hello ${name}!`;
4.使用展开运算符进行数组和对象操作
// 合并数组
const combined = [...array1, ...array2];
// 复制对象
const clone = { ...original };
5.简化循环
// 遍历数组
const doubled = numbers.map(num => num * 2);
// 过滤数组
const evens = numbers.filter(num => num % 2 === 0);
6.简化判断
// 传统条件判断
let message;
if (isSuccess) {message = 'Operation successful';
} else {message = 'Operation failed';
}
// 三元运算
const message = isSuccess ? 'Operation successful' : 'Operation failed';
7.使用对象解构和默认参数简化函数参数
// 传统参数设置默认值
function greet(name) {const finalName = name || 'Guest';console.log(`Hello, ${finalName}!`);}// 对象解构和默认参数简化function greet({ name = 'Guest' }) {console.log(`Hello, ${name}!`);}
8.使用函数式编程概念如纯函数和函数组合
// 纯函数
function add(a, b) {return a + b;}// 函数组合const multiplyByTwo = value => value * 2;const addFive = value => value + 5;const result = addFive(multiplyByTwo(3));
9.使用对象字面量简化对象的创建和定义
// 传统对象创建
const person = {firstName: 'John',lastName: 'Doe',age: 30,};// 对象字面量简化const firstName = 'John';const lastName = 'Doe';const age = 30;const person = { firstName, lastName, age };
10.使用适当的命名和注释来提高代码可读性
11.条件判断优化
if else
// param {status} status 活动状态:1:成功 2:失败 3:进行中 4:未开始
let txt = '';
if (status == 1) {txt = "成功";
} else if (status == 2) {txt = "失败";
} else if (status == 3) {txt = "进行中";
} else {txt = "未开始";
}
switch case
let txt = '';
switch (status) {case 1:txt = "成功";break;case 2:txt = "成功";break;case 3:txt = "进行中";break;default:txt = "未开始";
}
判断封装
// 好的
shouldShowSpinner(fsm, listNode){return fsm.state === 'fetching' && isEmpty(listNode)
}
if(shouldShowSpinner(fsm, listNode)){//...doSomething
}
Object.assign给默认对象赋默认值
const menuConfig = {title: 'Order',buttonText: 'Send',cancellable: true
};
function createMenu(config) {Object.assign({title: 'Foo',body: 'Bar',buttonText: 'Baz',cancellable: true }, config) // {} 目标对象,config 源对象
}
createMenu(menuConfig);
备注:
Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。简单来说,就是Object.assign()是对象的静态方法,可以用来复制对象的可枚举属性到目标对象,利用这个特性可以实现对象属性的合并。
Object.assign(target, ...sources)参数: target--->目标对象source--->源对象返回值:target,即目标对象
函数参数“两个”以下最好
// 不好的
function createMenu(title, body, buttonText, cancellable) {// ...
}
// 好的
const menuConfig = {title: 'Foo',body: 'Bar',buttonText: 'Baz',cancellable: true
};
function createMenu(menuConfig){// ...
}
12.使用解释形语言
13.让对象拥有私有成员-通过闭包来实现
// 不好的
const Employee = function(name) {this.name = name;
};
Employee.prototype.getName = function getName() {return this.name;
};
const employee = new Employee('John Doe');
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined
// 好的
const Employee = function(name){this.getName = function(){return name}
}
const employee = new Employee('John Doe');
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined