懂JavaScript;在返回函数之后递增变量值

时间:2017-09-19 10:19:15

标签: javascript

很抱歉,如果这个问题是基本的,但我正在学习JavaScript的闭包,我正在创建一个猜谜游戏,这是我的代码

function guessingGame(amount){
var answer = Math.floor(Math.random() * 10);
var tries = 0;
return function(guess){
  if(guess === answer){
    console.log('Got it')
    return ++tries
  }
  else if(guess > answer){
    console.log('You are too high')
  return ++tries
  }
  else if(guess < answer){
    console.log('You are too low')
  return ++tries
  } 
  if(tries > amount){
    console.log('Number of tries exceeded')
   }
  }
}

我想让if(tries > amount)测试工作,但我确信我做错了。请任何帮助,谢谢,

3 个答案:

答案 0 :(得分:2)

if(guess === answer){

  }
else if(guess > answer){
  }
else if(guess < answer){
  }

其中一个条件总是为真,因此代码的最后一部分永远不会被执行

答案 1 :(得分:2)

这应该可以解决问题

function guessingGame(amount){
    var answer = Math.floor(Math.random() * 10);
    var tries = 0;
    return function(guess){
        if(tries > amount){
            console.log('Number of tries exceeded')
            return;
       }
       if(guess === answer){
           console.log('Got it')
           return ++tries
       }
       else if(guess > answer){
           console.log('You are too high')
           return ++tries
       }
       else if(guess < answer){
           console.log('You are too low')
           return ++tries
       } 
    }
}

您只需要在检查之前将条件作为if语句之一进行检查,然后检查将始终评估为true,并且该检查是无法访问的代码。

答案 2 :(得分:0)

在任何退货之前保持您的状况tries > amount。像这样更新您的代码

function guessingGame(amount){
var answer = Math.floor(Math.random() * 10);
var tries = 0;
return function(guess){
  if(tries > amount){
    console.log('Number of tries exceeded')
   }
  if(guess === answer){
    console.log('Got it')
    return ++tries
  }
  else if(guess > answer){
    console.log('You are too high')
  return ++tries
  }
  else if(guess < answer){
    console.log('You are too low')
  return ++tries
   
  
  }
  }
}
var guess = guessingGame(2);
console.log(guess(1));
console.log(guess(2));
console.log(guess(3));
console.log(guess(4));