简体   繁体   中英

Looking up fixed key value pairs

I am trying to code some functions to look up area codes based on the specified city. Two questions... 1) Why is my else statement not working? 2) How do I retrieve the value of the key that matches the user input?

 let areaCodes = { 'San Francisco': 102, 'Portland': 200, 'Boston': 10 } // prompt user for input and return output function userPrompt(list) { var ans = prompt('Would you like to look up a city by area code? (Y/N)'); if (ans = 'Y') { return Object.keys(list); } else { return 'What would you like to do?'; } } // analyse input function inputAnalysis(list) { var input = prompt('Which city would you like to look up?'); if (list.hasOwnProperty(input)) { console.log('The area code for ' + input + ' is: ' + list.valueOf(input)) } } 

your code is correct, just you need to remove one error from your userPrompt function .

function userPrompt (list) {
    var ans = prompt('Would you like to look up a city by area code? (Y/N)');

    if (ans == 'Y') { // <--- Make it "==" to work.
        return Object.keys(list);
    }
    else 
    {
        return 'What would you like to do?'; 
    }
}

and

function inputAnalysis(list) {
  var input = prompt('Which city would you like to look up?');

  if (list.hasOwnProperty(input)) {
    console.log('The area code for ' + input + ' is: ' + list[input]) // <--- to avoid [object object] error.
  }
}

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