如何简化JavaScript中的多个if else条件- React JS



如何以更简单的方式减少这个条件逻辑。如果状态值增加,条件继续下去,请帮助写一个干净的代码

const getColor = status => {
if (status === 'positive') {
return { backgroundColor: 'red' }
} else if (status === 'negative') {
return { backgroundColor: 'orange' }
} else if (status === 'neutral') {
return { backgroundColor: 'blue' }
}else if (status === 'none') {
return { backgroundColor: 'white' }
}else if (status === 'all') {
return { backgroundColor: 'black' }
}
}
<p style={getColor(result.sentiment_label)}>test</p>

对于您的用例,您可以使用switch:

switch (status) {
case 'positive':
return { backgroundColor: 'red' }
case 'negative':
return { backgroundColor: 'orange' }
...
default:
return { backgroundColor: 'black' }
}

另一个更短(但更难阅读)的解决方案是:

const statusBgColorMap = {
positive: 'red',
negative: 'orange',
...
}
return { backgroundColor: statusBgColorMap[status] || 'defaultcolor' }

使用object代替:

const COLORS = {
positive: "red",
negative: "orange",
neutrla: "blue",
none: "white",
all: "black",
}
<p style={{ backgroundColor: COLORS[result.sentiment_label] }}>
test
</p>

switch statement maybe?它肯定会读得更好:

const getColor = status => {
switch(status) {
case 'positive':
return 'red';
break;
case ''negative:
return 'orange'
break;
case ''neutral:
return 'blue'
break;
case ''none:
return 'white'
break;
default:
return 'black'
}
}

<p style={{backgroundColor: getColor(result.sentiment_label) }}>test</p>

一种方法是:

const getColor = status => {
if (status === 'positive') return { backgroundColor: 'red' }
if (status === 'negative') return { backgroundColor: 'orange'}
if (status === 'neutral') return { backgroundColor: 'blue' }
if (status === 'none') return { backgroundColor: 'white' }
if (status === 'all') return { backgroundColor: 'black' }
return null
}

考虑到在if语句中返回的next条件不会运行,因此不需要else if。此外,考虑到每个if语句只有一个命令,您可以删除大括号

最新更新