dimanche 31 octobre 2021

Is there an easier way to combine several if statements using an array in javascript

I have a form where a user enters their address. This then checks their address against several destinations in the UK to see which city is their nearest.

I want each destination to have different prices, for example London, UK = 50, Birmingham, UK = 200 etc.

I have written a pretty rudimentary if statement which checks the city that is returned and calculates the price. However, I'm wondering if there is a neater solution to this as it feels a bit obtuse:

if(closestCities[0].cityName == "Coventry, UK") {
  travelExpenses = 10;
} else if (closestCities[0].cityName == "London, UK"){
  travelExpenses = 50;
} else if (closestCities[0].cityName == "Margate, UK"){
  travelExpenses = 100;
} else if (closestCities[0].cityName == "Bristol, UK"){
  travelExpenses = 20;
} else if (closestCities[0].cityName == "Tamworth, UK"){
  travelExpenses = 15;
} else if (closestCities[0].cityName == "Birmingham, UK"){
  travelExpenses = 200;
} else {
  travelExpenses = 30;
}

Aucun commentaire:

Enregistrer un commentaire