javascript - 为什么最后一个函数没有返回你毫无疑问

标签 javascript

我应该让你在队列中没有问题,因为最后三个问题我不知道为什么最后一个控制台应该返回你在队列中没有问题。它会返回当前问题还是我的代码有任何问题。

var student = {};
student.firstName = 'W';
student.lastName = 'H';
student.age = '21';
student.school = 'UofA';
student.questionQueue = [];
student.hasQuestion = false;
student.greeting = function(){return "Hello, my name is " + this.firstName;}
student.aboutMe = function(){return "My full name is " + this.firstName + " " + this.lastName + ", " + "I am " + this.age + " years old and I am a student at " + this.school;}
student.askQuestion = function(question){
  this.questionQueue.push(question);
  this.hasQuestion = !this.hasQuestion;
  return "A question has been added to your queue";
}
student.answerQuestion = function(){
  if(student.hasQuestion === true){
    var currentQuestion = this.questionQueue.pop();
    if (student.questionQueue.length === 0) {
      student.hasQuestion === false;
    }
    return currentQuestion;
  }
  else if(student.hasQuestion === false){
    return "You have no questions in your queue";
  }
}

console.log('Greet Test:', student.greeting());
console.log('AboutMe Test:', student.aboutMe());
console.log('Answer Question Test:', student.answerQuestion());
console.log('Ask Question Test:', student.askQuestion('Why is the Earth flat?'));
console.log('Ask Question Test:', student.askQuestion('Why is the sky green?'));
console.log('Ask Question Test:', student.askQuestion('Why don\'t birds have wings'));
console.log('Answer Question Test:', student.answerQuestion());
console.log('Answer Question Test:', student.answerQuestion());
console.log('Answer Question Test:', student.answerQuestion());
console.log('Answer Question Test:', student.answerQuestion());

最佳答案

this.hasQuestion = !this.hasQuestion;

必须是

this.hasQuestion = true;

通过提问,您只是一次又一次地反转 bool 值。这没有任何意义。

if (student.questionQueue.length === 0)
  student.hasQuestion === false;

必须是

if (student.questionQueue.length === 0)
  student.hasQuestion = false;

您只是在测试 bool 值,同时您想要更改它。

关于javascript - 为什么最后一个函数没有返回你毫无疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58595787/

相关文章:

javascript - 使用 Phonegap 访问文件

javascript - 删除表的内容并使用 JavaScript 替换

javascript - 在 Which browser can I use "dispatchevent"in the background tab?

javascript - 无法从 jQuery ajax 调用获取 json 数据

javascript - 如何在 Angular 2 中使用 jQuery UI

javascript - bootstrap typeahead 未获取结果

javascript - 为什么 jquery 的 .load() 会忽略 <script>?

javascript - jQuery 替换特定文本

javascript - 在页面上加载高级 jQuery 版本

javascript - 如何在 Javascript 的 SELECT 元素中设置或选择选项