查找固定键值对

时间:2019-05-17 09:23:37

标签: javascript

我正在尝试对一些功能进行编码,以根据指定的城市查找区号。 两个问题... 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))
  }
}

2 个答案:

答案 0 :(得分:1)

您的代码正确,只是您需要从 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.
  }
}

答案 1 :(得分:-1)

嗨,请看一眼,希望它对您有用。

您需要将对象放入函数中,以使键的检索值与用户输入相匹配。

$(function(){
    userPrompt();
});

// prompt user for input and return output

function userPrompt(list) {
  let areaCodes = {
    'San Francisco': 102,
    'Portland': 200,
    'Boston': 10
  }
  var ans = prompt('Would you like to look up a city by area code? (Y/N)');

  if (ans) {
    if(areaCodes[ans]){
            return areaCodes[ans]; 
    }else{
        return 'not found.';
    }

  } else {

    return 'What would you like to do?';
  }
}