js中多个if else的优化方式?

前人的代码 通过后台返回的天气情况字段 来返回对应的天气图标

  document.getElementById("weather-font").innerHTML = "&nbsp" + weather;

if (weather == "晴" || weather == "晴转多云") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_fine.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_fine.jpg";

} else if (weather == "多云" || weather == "多云转晴" || weather == "多云转阵雨" || weather == "多云转阴") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_cloudy.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_cloudy.jpg";

} else if (weather == "阴") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_sky.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_sky.jpg";

} else if (weather == "雾") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_fog.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_fog.jpg";

} else if (weather == "风") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_wind.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_wind.jpg";

} else if (weather == "小雨" || weather == "中雨" || weather == "小到中雨" || weather == "中到大雨" ||

weather == "大雨" || weather == "暴雨" || weather == "小到暴雨" || weather == "中到暴雨") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_rainy.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_rainy.jpg";

} else if (weather == "大到暴雨") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_rainstorm.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_rainstorm.jpg";

} else if (weather == "阵雨") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_rainysh.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_rainysh.jpg";

} else if (weather == "雷雨" || weather == "雷阵雨") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_thunder.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_thunder.jpg";

} else if (weather == "雪") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_snow.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_snow.jpg";

} else if (weather == "雨加雪") {

//document.getElementById("weather-img").style.backgroundImage = "URL('../Images/right_weather_raisnow.jpg')";

document.getElementById("weather-img").src = "../Images/right_weather_raisnow.jpg'";

}

var PMvalue = str.split('"pm25":"')[1].split('",')[0];

document.getElementById("pm").innerHTML = " " + PMvalue;

if (quality == "重度污染") {

document.getElementById("pm-color").style.color = "#be0606";

} else if (quality == "轻度污染") {

document.getElementById("pm-color").style.color = "#ff0000";

} else if (quality == "良") {

document.getElementById("pm-color").style.color = "#267405";

} else {

document.getElementById("pm-color").style.color = "#3dc404";

}

这种代码 怎么优化


回答:

可以维护一份数据字典通过映射处理

var urlMap = {

‘晴’:'../Images/right_weather_fine.jpg',

‘多云’:'../Images/right_weather_fine.jpg',

}

document.getElementById("weather-img").style.backgroundImage = "URL("+urlMap[weather]+")";


回答:

做一个映射表

let srcs = {

"晴": '../Images/right_weather_fine.jpg',

"晴转多云": '../Images/right_weather_fine.jpg',

"多云": '../Images/right_weather_cloudy.jpg',

"多云转晴": '../Images/right_weather_cloudy.jpg',

"多云转阵雨": '../Images/right_weather_cloudy.jpg',

"多云转阴": '../Images/right_weather_cloudy.jpg'

}

document.getElementById("weather-img").src = srcs[weather] || ''

或者使用switch

let src = ''

switch(weather){

case "晴":

case "晴转多云":

src = '../Images/right_weather_fine.jpg';

break;

case "多云":

case "多云转晴":

case "多云转阵雨":

case "多云转阴":

src = '../Images/right_weather_cloudy.jpg';

break;

}

document.getElementById("weather-img").src = src


回答:

1、扩展性强
2、可读、可维护性强
3、你说的 weather === '晴' || weather === '晴转多云' 这种方式也解决了

const map = [

{

filter: (weather: string) => weather === '阵雨',

image: '../Images/right_weather_fine.jpg',

},

{

filter: (weather: string) => weather === '晴' || weather === '晴转多云',

image: '../Images/right_weather_fine.jpg',

},

{

filter: (weather: string) =>

weather === '多云' ||

weather === '多云转晴' ||

weather === '多云转阵雨' ||

weather === '多云转阴',

image: '../Images/right_weather_cloudy.jpg',

},

{

filter: (weather: string) =>

weather === '小雨' ||

weather === '中雨' ||

weather === '小到中雨' ||

weather === '中到大雨' ||

weather === '大雨' ||

weather === '暴雨' ||

weather === '小到暴雨' ||

weather === '中到暴雨',

image: '../Images/right_weather_rainy.jpg',

},

];

export const filterMap = (weather: string) => {

const filterMapItem = map.find((item) => item.filter(weather));

if (!filterMapItem) {

return '';

}

return filterMapItem.image;

};

console.log('filterMap', filterMap('晴'));


回答:

当作一个学习经历的分享吧。
每次做优化,有两点:

  1. 要注意就是一次优化一个点,优化好了再进行下一次优化。这样自己理解成本会降低,就像解不等式,约分和去括号不要一次性算完,因为自己的算力可能不够,容易出错。
  2. 先观察,再修改。

然后我们一起来尝试优化。

重复的语句进行封装

我们提取出两个函数

function 设置天气(weather) {

document.getElementById("weather-img").src = `../Images/right_weather_${weather}.jpg`;

}

function 设置污染(quality) {

document.getElementById("pm-color").style.color = quality;

}

那么原文变成了

document.getElementById("weather-font").innerHTML = "&nbsp" + weather;

if (weather == "晴" || weather == "晴转多云") {

设置天气('fine')

} else if (weather == "多云" || weather == "多云转晴" || weather == "多云转阵雨" || weather == "多云转阴") {

设置天气('cloudy')

} else if (weather == "阴") {

设置天气('sky')

} else if (weather == "雾") {

设置天气('fog')

} else if (weather == "风") {

设置天气('wind')

} else if (weather == "小雨" || weather == "中雨" || weather == "小到中雨" || weather == "中到大雨" ||

weather == "大雨" || weather == "暴雨" || weather == "小到暴雨" || weather == "中到暴雨") {

设置天气('rainy')

} else if (weather == "大到暴雨") {

设置天气('rainstorm')

} else if (weather == "阵雨") {

设置天气('rainysh')

} else if (weather == "雷雨" || weather == "雷阵雨") {

设置天气('thunder')

} else if (weather == "雪") {

设置天气('snow')

} else if (weather == "雨加雪") {

设置天气('raisnow')

}

var PMvalue = str.split('"pm25":"')[1].split('",')[0];

document.getElementById("pm").innerHTML = " " + PMvalue;

if (quality == "重度污染") {

设置污染( "#be0606")

} else if (quality == "轻度污染") {

设置污染( "#ff0000")

} else if (quality == "良") {

设置污染( "#267405")

} else {

设置污染( "#3dc404")

}

重复的判断词使用 swich语句

function 设置天气(weather) {

document.getElementById("weather-img").src = `../Images/right_weather_${weather}.jpg`;

}

function 设置污染(quality) {

document.getElementById("pm-color").style.color = quality;

}

switch (weather) {

case "晴": case "晴转多云":

设置天气('fine')

break;

case "多云": case "多云转晴": case "多云转阵雨": case "多云转阴":

设置天气('cloudy')

break;

case "阴":

设置天气('sky')

break;

case "雾":

设置天气('fog')

break;

case "风":

设置天气('wind')

break;

case "小雨": case "中雨": case "小到中雨": case "中到大雨":

case "大雨": case "暴雨": case "小到暴雨": case "中到暴雨":

设置天气('rainy')

break;

case "大到暴雨":

设置天气('rainstorm')

break;

case "阵雨":

设置天气('rainysh')

break;

case "雷雨": case "雷阵雨":

设置天气('thunder')

break;

case "雪":

设置天气('snow')

break;

case "雨加雪":

设置天气('raisnow')

break;

}

document.getElementById("weather-font").innerHTML = "&nbsp" + weather;

var PMvalue = str.split('"pm25":"')[1].split('",')[0];

document.getElementById("pm").innerHTML = " " + PMvalue;

switch (quality) {

case '重度污染':

设置污染("#be0606")

break;

case '轻度污染':

设置污染("#ff0000")

break;

case '良':

设置污染("#267405")

break;

default:

设置污染("#3dc404")

break;

}

再次观察,发现其实就是多个值对一个值的映射关系

那我们处理办法就是用Object,但如何设计,就是一个要考虑的问题了。内存和效率必然会损失一个。
我选择枚举封装到函数中

function 设置天气(weather) {

const 天气 = {

fine: ["晴", "晴转多云",],

cloudy: ["多云", "多云转晴", "多云转阵雨", "多云转阴",],

sky: ['阴'],

}

let today = Object.entries(天气)

.find(([word, chinese]) => chinese.includes(weather))

[0]

return `../Images/right_weather_${today}.jpg`;

}

function 设置污染(quality) {

const 污染 = {

重度污染: 'be0606',

轻度污染: 'ff0000',

良: '267405',

default:'3dc404'

}

let today = 污染[quality] || 污染.default

return `#${today}`;

}

那么原文就变成了

document.getElementById("weather-font").innerHTML = "&nbsp" + weather;

document.getElementById("weather-img").src = 设置天气(weather)

var PMvalue = str.split('"pm25","')[1].split('",')[0];

document.getElementById("pm").innerHTML = " " + PMvalue;

document.getElementById("pm-color").style.color = 设置污染(quality)


回答:

function getImage(text) {

const imageMap = {

'多云': 'image1',

'雷雨': 'image2',

'雷阵雨': 'image2'

}

return imageMap[text] || 'defaultImage'

}


回答:

我就写一段,你自己推就行。

function ABCDEFG(){

const el = document.getElementById("weather-img")

if(['晴','晴转多云'].includes(weather)){

...

} else if(['多云','多云转晴','多云转阵雨','多云转阴'].includes(weather)){ ...

...

也可以提取出来

const weatherDictList = [

{ typeList:['晴','晴转多云'], img: "./Images/right_weather_fine.jpg"},

...

}

const getWeatherInfo = (typeLabel) => {

return weatherDictList.find(item=>item.typeList.includes(typeLabel))

}

业务代码里面就只需要这样写就行了:

function ABCDEFG(){

const el = document.getElementById("weather-img")

const weatherData = getWeatherInfo(weather)

el.src(weatherData.img)

}


回答:

let srcs = {

'晴|晴转多云': '../Images/right_weather_fine.jpg',

'多云|多云转晴|多云转阵雨|多云转阴': '../Images/right_weather_yun.jpg',

'阴': '../Images/right_weather_yin.jpg',

}

function transMap (srcs) {

const res = {}

Object.entries(srcs).forEach(([key, value]) => {

const ckeys = key.split('|')

ckeys.forEach(ckey => {

res[ckey] = value

})

})

return res

}

const srcMap = transMap(srcs)

document.getElementById("weather-img").src = srcMap[weather]


回答:

js中多个if else的优化方式?

function getWeatherImg(weather) {

let weatherMap = new Map([

[['晴', '晴转多云'], '../Images/right_weather_fine.jpg'],

[['多云', '多云转晴', '多云转阵雨', '多云转阴'], '../Images/right_weather_cloudy.jpg']

]);

// 直接通过 has 获取对象,如果不存在则遍历查找,还找不到则赋值为空字符

let [key = [], src = ''] = weatherMap.get([weather]) || [...weatherMap.entries()].find(([key = []]) => key.includes(weather)) || [[], ''];

return src;

}

let weather = '多云';

document.getElementById("weather-font").innerHTML = "&nbsp" + weather;

document.getElementById("weather-img").src = getWeatherImg(weather);

function getPmColor(PMvalue) {

let pmMap = new Map([

["重度污染", "#be0606"],

["轻度污染", "#ff0000"],

["良", "#267405"],

]);

// 如果找不到则默认颜色

return pmMap.get(PMvalue) || "#3dc404"

}

var PMvalue = str.split('"pm25":"')[1].split('",')[0];

document.getElementById("pm").innerHTML = " " + PMvalue;

document.getElementById("pm-color").style.color = getPmColor(PMvalue);

使用了 Map 数组解构等新语法。
https://developer.mozilla.org...

以上是 js中多个if else的优化方式? 的全部内容, 来源链接: utcz.com/p/933218.html

回到顶部