gpt4 book ai didi

javascript - 变量中的字符串用作 if 语句的条件

转载 作者:行者123 更新时间:2023-11-30 12:18:20 24 4
gpt4 key购买 nike

我正在制作一张图表,如果有人访问某个地区的某个国家/地区(在本例中为亚洲),则将条形设为某种颜色。

 if (
d.visitCountry === "China" || d.visitCountry === "Japan" ||
d.visitCountry === "Afghanistan" || d.visitCountry === "Armenia" ||
d.visitCountry === "Azerbaijan" || d.visitCountry === "Bangladesh" ||
d.visitCountry === "Bhutan" || d.visitCountry === "Brunei Darussalam" ||
d.visitCountry === "Cambodia" || d.visitCountry === "Georgia" ||
d.visitCountry === "Hong Kong" || d.visitCountry === "India" ||
d.visitCountry === "Indonesia" || d.visitCountry === "Kazakhstan" ||
d.visitCountry === "North Korea" || d.visitCountry === "South Korea" ||
d.visitCountry === "Kyrgyzstan" || d.visitCountry === "Laos" ||
d.visitCountry === "Macau" || d.visitCountry === "Malaysia" ||
d.visitCountry === "Maldives" || d.visitCountry === "Mongolia" ||
d.visitCountry === "Myanmar" || d.visitCountry === "Nepal" ||
d.visitCountry === "Pakistan" || d.visitCountry === "Singapore" ||
d.visitCountry === "Sri Lanka" || d.visitCountry === "Taiwan" ||
d.visitCountry === "Tajikistan" || d.visitCountry === "Thailand" ||
d.visitCountry === "Timor Leste" || d.visitCountry === "Turkmenistan" ||
d.visitCountry === "Uzbekistan" || d.visitCountry === "Vietnam") {
returnColor = "red";
}

我使用的这种方法的问题是它冗长乏味。

有没有办法让它变成这样

var worldRegion = {
worldRegion.Asia = [ China, Japan, North Korea ... ]
worldRegion.northAmerica = [USA, Canada, Greenland ... ]
worldRegion.Africa = [ ... ]

if (d.visitCountry === worldRegion.Asia) /* this is obviously wrong */ {
returnColor = "red";
}
else if (d.visitCountry === worldRegion.northAmerica) /* this is obviously wrong */ {
returnColor = "blue";
}
return returnColor;

但显然该代码是错误的。

最佳答案

可以用一堆数组来做您所说的事情,但我可能会改用一个对象作为映射:

var countryColors = {
China: "red",
Japan: "red",
"North Korea": "red",
// ...
USA: "blue",
Canada: "blue",
Greenland: "blue"
};

请注意,具有有效字面名称的属性可以按字面意思书写,但没有有效字面名称的属性(如 North Korea,因为有空格)要放在引号中。或者您可以将它们全部放在引号中以保持一致性。

然后

returnColor = countryColors[d.visitCountry];

但是如果你想用一堆数组来做,使用Array#indexOf:如果结果不是-1,条目就在那里:

if (worldRegion.Asia.indexOf(d.visitCountry) !== -1) {
returnColor = "red";
}
else if (worldRegion.northAmerica.indexOf(d.visitCountry !== -1) {
returnColor = "blue";
}
// ...

旁注:如果您需要支持像 IE8 这样过时的浏览器,您可能需要一个用于 Array#indexOf 的垫片(polyfill)。搜索会找到一个。所有现代浏览器都内置了它。


旁注:我很确定格陵兰岛不在北美。 你知道什么,I'm wrong关于那个……

关于javascript - 变量中的字符串用作 if 语句的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31782653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com