简体   繁体   中英

Why i am getting result from "else if" even though "if" condition is true

Google reverse geocoding gives me result like this

results: [
{address_components: [
{long_name: "New York",
short_name: "NY",
types: ["neighborhood"]},]

{address_components: [
{long_name: "London",
short_name: "LN",
types: ["sublocality_level_1"]},]}]

here is code for getting result for long name of "neighborhood":

for (i = 0; i < response.results.length; i++) {
for (var acd = 0; acd < response.results[i].address_components.length; acd++) {
var fff =  response.results[i].address_components[acd];
var storableLocation;
if(fff.types.includes("neighborhood")) {
storableLocation = fff.long_name;
}else if (fff.types.includes("sublocality_level_1")){
storableLocation = fff.long_name;}}}

console.log(storableLocation) gives result - London.

Why it shows result for London if first condition is true? it should have consoled New York or i am mistaken ?

Because console.log(storableLocation) is outside of both loops, you are seeing the second value that was assigned to the var storableLocation . You are not seeing the first value assigned to the variable because by the time you console.log , the loops already finished and reassigned storableLocation to London in the else if statement.

Instead, you should do the following:

var results = [ {address_components: [
{long_name: "New York",
short_name: "NY",
types: ["neighborhood"]}]},

{address_components: [
{long_name: "London",
short_name: "LN",
types: ["sublocality_level_1"]}]}]

loop1:
for (i = 0; i < results.length; i++) {
   var storableLocation;
   loop2:
   for (var acd = 0; acd < results[i].address_components.length; acd++) {
       var fff =  results[i].address_components[acd];
       if(fff.types.includes("neighborhood")) {
          storableLocation = fff.long_name;
          console.log(storableLocation)
          break loop1;
       }
       else if (fff.types.includes("sublocality_level_1")){
          storableLocation = fff.long_name;
       }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM