javascript - strings in a variable to use as condition for if statement -
i'm making chart if person visits country in region (in case asia), make bar color.
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"; }
the problem method i'm using it's long , tedious.
is there way make it's this
var worldregion = { worldregion.asia = [ china, japan, north korea ... ] worldregion.northamerica = [usa, canada, greenland ... ] worldregion.africa = [ ... ] if (d.visitcountry === worldregion.asia) /* wrong */ { returncolor = "red"; } else if (d.visitcountry === worldregion.northamerica) /* wrong */ { returncolor = "blue"; } return returncolor;
obviously code wrong though.
you can you're talking bunch of arrays, i'd use object map instead:
var countrycolors = { china: "red", japan: "red", "north korea": "red", // ... usa: "blue", canada: "blue", greenland: "blue" };
note properties have valid literal names can written literally, ones don't have valid literal names (like north korea, because of space) put in quotes. or can put them in quotes consistency.
then
returncolor = countrycolors[d.visitcountry];
but if want bunch of arrays, use array#indexof
: if result not -1
, entry there:
if (worldregion.asia.indexof(d.visitcountry) !== -1) { returncolor = "red"; } else if (worldregion.northamerica.indexof(d.visitcountry !== -1) { returncolor = "blue"; } // ...
side note: if need support obsolete browsers ie8, may need shim (polyfill) array#indexof
. search turn 1 up. modern browsers have built-in.
side note: i'm pretty sure greenland isn't in north america. know, i'm wrong that...
Comments
Post a Comment