只有在找到或未找到结果的情况下,我该如何才能使用console.log?

时间:2016-12-19 21:18:16

标签: javascript javascript-objects

我正在为学习项目创建一个迷你搜索工具,我无法弄清楚为什么这个console.logs两次

var states = {
  North_Dakota: {capital: 'Bismarck', region: 'Mid-west'},
  Minnesota: {capital: 'Saint paul', region: 'Mid-west'},
  Montana: {capital: 'Helena', region: 'Mid-west'},
  Wisconsin: {capital: 'Madison', region: 'Mid-west'}
};

var searchCapitals = function(givenWord){
  for (var key in states) {
    if (givenWord.toLowerCase() === key.toLowerCase()) {
      console.log('Search found: ' + key + ' (capital: ' + states[key].capital + ', region: ' + states[key].region + ')')
    } else (givenWord.toLowerCase() != key.toLowerCase()) {
      console.log('No results found.')
    }
  }
};

searchCapitals('wisconsin');

它应该只输出一次,因为'wisconsin'是匹配的吗?然而,它记录了每个对象项的字符串'找不到结果'。非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

尝试在循环中设置boolean而不是登录循环,如果已循环整个对象或数组,请尝试记录:



var states = {
  North_Dakota: {capital: 'Bismarck', region: 'Mid-west'},
  Wisconsin: {capital: 'Madison', region: 'Mid-west'},
  Minnesota: {capital: 'Saint paul', region: 'Mid-west'},
  Montana: {capital: 'Helena', region: 'Mid-west'}
};

var searchCapitals = function(givenWord){
  var found = false;
  var foundKey = "";
  
  for (var key in states) {
      
      console.log(key);
    if (givenWord.toLowerCase() === key.toLowerCase()) {
      found = true;
      foundKey = key;
      break; // stop searching if you found a matching pair
    }
  }
      
  if(found)
    console.log('Search found: ' + foundKey + ' (capital: ' + states[foundKey].capital + ', region: ' + states[foundKey].region + ')')
  else
    console.log('No results found.')
};

searchCapitals('wisconsin');