繁体   English   中英

查找固定键值对

[英]Looking up fixed key value pairs

我正在尝试对一些功能进行编码,以根据指定的城市查找区号。 两个问题... 1)为什么我的else语句不起作用? 2)如何检索与用户输入匹配的键的值?

 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)) } } 

您的代码是正确的,只需要从userPrompt函数中删除一个错误即可。

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?'; 
    }
}

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.
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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