在 JavaScript 开发中,传统switch
语句存在冗长、易出错、难维护等弊端。现代 JavaScript 提供了对象映射、Map 数据结构等替代方案,能大幅简化条件逻辑。同时,结合变量声明优化、箭头函数、异步编程改进等技巧,可让代码更简洁高效,显著提升开发效率与代码质量 。
传统 switch 语句的问题
传统 switch 语句存在冗长、易出错、难维护和可读性差等问题,下面是一个传统 switch 语句的示例:
function getDayName(day) {
switch (day) {
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
case 7:
return 'Sunday';
default:
return 'Invalid day';
}
}
console.log(getDayName(2));
使用对象替代 switch
对象映射是替代简单 switch 语句的有效方式,它更简洁:
function getDayName(day) {
const dayMap = {
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday',
7: 'Sunday'
};
return dayMap[day] || 'Invalid day';
}
console.log(getDayName(2));
处理复杂逻辑
当每个分支包含复杂逻辑时,可把函数作为对象的值:
function performAction(action) {
const actions = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => a / b
};
const actionFn = actions[action];
if (!actionFn) {
return 'Invalid action';
}
return actionFn(10, 5);
}
console.log(performAction('add'));
使用 Map 数据结构
ES6 的 Map 数据结构比对象字面量功能更强大,适合键不限于字符串等场景:
function getDayName(day) {
const dayMap = new Map([
[1, 'Monday'],
[2, 'Tuesday'],
[3, 'Wednesday'],
[4, 'Thursday'],
[5, 'Friday'],
[6, 'Saturday'],
[7, 'Sunday']
]);
return dayMap.get(day) || 'Invalid day';
}
console.log(getDayName(2));
函数映射和链式操作
Map 适合实现命令模式或策略模式,示例如下:
class Calculator {
constructor() {
this.operations = new Map([
['+', (a, b) => a + b],
['-', (a, b) => a - b],
['*', (a, b) => a * b],
['/', (a, b) => a / b],
['%', (a, b) => a % b]
]);
}
calculate(a, operator, b) {
const operation = this.operations.get(operator);
if (!operation) {
throw new Error(`Unsupported operator: ${operator}`);
}
return operation(a, b);
}
addOperation(operator, fn) {
this.operations.set(operator, fn);
return this;
}
}
const calc = new Calculator()
.addOperation('log', (a, b) => Math.log(a) / Math.log(b));
console.log(calc.calculate(10, '+', 5));
console.log(calc.calculate(10, 'log', 10));
通过运用对象映射和 Map 数据结构,能让 JavaScript 代码更简洁、优雅且易于维护。
还有哪些代码优化技巧?
变量声明与作用域
使用 const 和 let 替代 var:const 和 let 具有块级作用域,能避免变量提升带来的问题,增强代码的可预测性。
function testVar() {
if (true) {
var x = 10;
}
console.log(x);
}
function testLet() {
if (true) {
let y = 10;
}
}
减少全局变量的使用:全局变量易引发命名冲突和代码难以维护,尽量将变量的作用域限制在函数或模块内部。
函数优化
箭头函数:它是一种更简洁的函数定义方式,特别适合简单的回调函数,并且它没有自己的 this、arguments、super 或 new.target,this 值继承自外层函数。
const numbers = [1, 2, 3];
const squared = numbers.map(function(num) {
return num * num;
});
const squaredWithArrow = numbers.map(num => num * num);
函数柯里化:把多参数函数转换为一系列单参数函数,可提高函数的复用性。
function add(a, b) {
return a + b;
}
function curriedAdd(a) {
return function(b) {
return a + b;
};
}
const add5 = curriedAdd(5);
console.log(add5(3));
循环优化
避免在循环中重复计算:如果循环条件或循环体中有重复计算的部分,应提前计算好。
const arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
}
const len = arr.length;
for (let i = 0; i < len; i++) {
}
使用 for...of 或数组方法替代传统 for 循环:for...of 语法更简洁,数组方法(如 map、filter、reduce 等)能让代码更具声明性。
const numbers = [1, 2, 3];
for (const num of numbers) {
console.log(num);
}
numbers.forEach(num => console.log(num));
条件判断优化
三元运算符:对于简单的条件判断,使用三元运算符可以让代码更简洁。
let result;
if (x > 10) {
result = 'Greater than 10';
} else {
result = 'Less than or equal to 10';
}
const resultWithTernary = x > 10 ? 'Greater than 10' : 'Less than or equal to 10';
逻辑与(&&)和逻辑或(||)短路求值:可以简化条件判断和赋值操作。
const name = user.name || 'Guest';
const isAdmin = true;
isAdmin && showAdminPanel();
异步编程优化
使用 async/await 替代回调地狱:async/await 让异步代码看起来更像同步代码,提高了代码的可读性和可维护性。
function getData(callback) {
setTimeout(() => {
const data = { message: 'Hello' };
callback(data);
}, 1000);
}
getData(data => {
console.log(data.message);
});
function getData() {
return new Promise(resolve => {
setTimeout(() => {
const data = { message: 'Hello' };
resolve(data);
}, 1000);
});
}
async function main() {
const data = await getData();
console.log(data.message);
}
main();
性能优化
防抖和节流:在处理高频事件(如 resize、scroll、input 等)时,使用防抖和节流可以减少不必要的函数调用,提高性能。
function debounce(func, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
function throttle(func, limit) {
let inThrottle;
return function() {
const context = this;
const args = arguments;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
——The End——
该文章在 2025/4/30 17:59:07 编辑过