查找固定的钥匙值对

  • 本文关键字:钥匙 查找 javascript
  • 更新时间 :
  • 英文 :


我正在尝试编码一些功能,以根据指定的城市查找区域代码。两个问题...1(为什么我的其他陈述不起作用?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.
  }
}

最新更新