优化前的函数:

const setZHRowColor = (colorLevel: '' | '0' | '1' | '2') => { if (colorLevel === '0') { Object.assign(styleObj, { backgroundColor: ZHRedRowColor }) } else if (colorLevel === '1') { Object.assign(styleObj, { backgroundColor: ZHBlueRowColor }) } else if (colorLevel === '2') { Object.assign(styleObj, { backgroundColor: ZHGreenRowColor }) }}

改进后的函数:

const setZHRowColor = (colorLevel: '' | '0' | '1' | '2') => { const colorMap = { '0': ZHRedRowColor, '1': ZHBlueRowColor, '2': ZHGreenRowColor }; Object.assign(styleObj, { backgroundColor: colorMap[colorLevel] || 'transparent' });}

使用对象代替 if-else 分支,将颜色值存储在对象中,根据传入的参数 colorLevel 直接取出对应的颜色值,避免了大量的 if-else 分支。同时,如果传入的 colorLevel 不是 0、1、2 中的任何一个,将会使用透明背景色。

优点:

  • 代码更加简洁易读。* 减少了 if-else 语句,提高了代码效率。* 处理了无效参数的情况,提高了代码的健壮性。
优化 JavaScript 函数:使用对象替代 if-else 语句设置行颜色

原文地址: http://www.cveoy.top/t/topic/lXaP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录