LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

还在用switch?JavaScript 这些替代方案值得拥有

admin
2025年4月30日 17:59 本文热度 135

在 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(105);}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 具有块级作用域,能避免变量提升带来的问题,增强代码的可预测性。

// 使用 varfunction testVar() {    if (true) {        var x = 10;    }    console.log(x); // 输出 10}// 使用 letfunction testLet() {    if (true) {        let y = 10;    }    // console.log(y);  // 报错,y 不在此作用域}

减少全局变量的使用:全局变量易引发命名冲突和代码难以维护,尽量将变量的作用域限制在函数或模块内部。

函数优化

箭头函数:它是一种更简洁的函数定义方式,特别适合简单的回调函数,并且它没有自己的 this、arguments、super 或 new.target,this 值继承自外层函数。

// 传统函数const numbers = [123];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)); // 输出 8

循环优化

避免在循环中重复计算:如果循环条件或循环体中有重复计算的部分,应提前计算好。

const arr = [12345];// 不好的写法for (let i = 0; i < arr.length; i++) {    // 每次循环都计算 arr.length}// 好的写法const len = arr.length;for (let i = 0; i < len; i++) {    // 只计算一次长度}

使用 for...of 或数组方法替代传统 for 循环:for...of 语法更简洁,数组方法(如 map、filter、reduce 等)能让代码更具声明性。

const numbers = [123];// 使用 for...offor (const num of numbers) {    console.log(num);}// 使用数组方法numbers.forEach(num => console.log(num));

条件判断优化

三元运算符:对于简单的条件判断,使用三元运算符可以让代码更简洁。

// 传统 if-elselet 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);});// async/await 示例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 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved