【问题标题】:Add object value to score based on propety name根据属性名称将对象值添加到分数
【发布时间】:2020-05-18 16:53:53
【问题描述】:

我正在尝试根据属性名称添加对象的值。我创建了一个测验并为每个选项(属性名称)分配了一个答案分数。我需要将choices.score 添加到this.score。例如,如果他们选择快乐,则将 6 添加到 this.score

其他一切都正常工作,我只是不知道在选择选项时如何将对象值添加到分数中。

function Quiz(questions) {
    this.score = 0;
    this.questions = questions;
    this.questionIndex = 0;
}
 
Quiz.prototype.getQuestionIndex = function() {
    return this.questions[this.questionIndex];
}
 
Quiz.prototype.guess = function(answer) {

        this.score++ ; //HERE IS WHERE I NEED TO ADD THE SCORE FROM THE SELECTED CHOICE
// I would like it to be this.score + choice.score but cant figure it out
        this.questionIndex++;
}
 
Quiz.prototype.isEnded = function() {
    return this.questionIndex === this.questions.length;
}
 
 
function Question(text, choices, score,both) {
    this.text = text;
    this.choices = Object.keys(choices);
    this.score = Object.values(choices);
    this.both = Object.entries(choices);
}

Question.prototype.isCorrectAnswer = function(choice) {
    return this.answer === choice;
}
 
 
function populate() {
    if(quiz.isEnded()) {
        showScores();
    }
    else {
        // show question
        var element = document.getElementById("question");
        element.innerHTML = quiz.getQuestionIndex().text;
 
        // show options
        var choices = quiz.getQuestionIndex().choices;
        for(var i = 0; i < choices.length; i++) {
            var element = document.getElementById("choice" + i);
            element.innerHTML = choices[i];
            guess("btn" + i, choices[i]);
        }
 
        showProgress();
    }
};


function guess(id, guess) {
    var button = document.getElementById(id);
    button.onclick = function() {
        quiz.guess(guess);
        populate();
    }
};
 
 
function showProgress() {
    var currentQuestionNumber = quiz.questionIndex + 1;
    var element = document.getElementById("progress");
    element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
 
function showScores() {
    var gameOverHTML = "<h1>Result</h1>";
    gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
    var element = document.getElementById("quiz");
    element.innerHTML = gameOverHTML;
};
 
// create questions here
var questions = [
    new Question("How are you feeling today?",{'very sad': "1", 'sad':"3",'happy':"6", 'very happy':"9"}),
    new Question("How angry are you today?",{'very angry': "1", 'little angry':"3",'not angry':"6", 'very happy':"9"})
];
console.log(questions);
// create quiz
var quiz = new Quiz(questions);
 
// display quiz
populate();
 <div class="grid">
        <div id="quiz">
            <h1>Self Assessment</h1>
            <hr style="margin-bottom: 20px">

            <p id="question"></p>
 
            <div class="buttons">
                <button id="btn0"><span id="choice0"></span></button>
                <button id="btn1"><span id="choice1"></span></button>
                <button id="btn2"><span id="choice2"></span></button>
                <button id="btn3"><span id="choice3"></span></button>
            </div>
            <hr style="margin-top: 50px">
            <footer>
                <p id="progress">Question x of y</p>
            </footer>
        </div>
    </div>

【问题讨论】:

  • this.score 中有什么内容?看来你有对象值
  • this.score 从 0 开始,但我需要从问题对象中添加分数值。例如:new Question("你今天感觉怎么样?",{'非常难过': "1", '难过':"3",'开心':"6", '非常开心':"9"} ) 如果他们选择悲伤,我在 this.score 上加 3
  • 我建议将分数从测验中移出。
  • 你可以添加基本的 HTM 来运行它吗
  • 我将 HTML 添加到问题的底部

标签: javascript arrays oop


【解决方案1】:

查看您的代码后..我试图找到解决方案..请参考以下答案:

您可以键入同一个数组,而不是在键值单独的数组中进行转换。这样键将是要显示的文本,值将是分数。当用户选择发送两者并获得答案时。

工作样本:

function Quiz(questions) {
  this.score = 0;
  this.questions = questions;
  this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function () {
  return this.questions[this.questionIndex];
};

Quiz.prototype.guess = function (answer) {
  this.score += Number(answer[1]);

  this.questionIndex++;
};

Quiz.prototype.isEnded = function () {
  return this.questionIndex === this.questions.length;
};

function Question(text, choices, score, both) {
  this.text = text;
  this.choices = Object.entries(choices);
  this.both = Object.entries(choices);
}

Question.prototype.isCorrectAnswer = function (choice) {
  return this.answer === choice;
};

function populate() {
  if (quiz.isEnded()) {
    showScores();
  } else {
    // show question
    var element = document.getElementById("question");
    element.innerHTML = quiz.getQuestionIndex().text;

    // show options
    const question = quiz.getQuestionIndex(); /// this line
    //console.log(question)
    var choices = question.choices;
    for (var i = 0; i < choices.length; i++) {
      var element = document.getElementById("choice" + i);
      element.innerHTML = choices[i][0];
      guess("btn" + i, choices[i]); /// this line
    }

    showProgress();
  }
}

function guess(id, guess) {
  var button = document.getElementById(id);
  button.onclick = function () {
    quiz.guess(guess); /// this line
    populate();
  };
}

function showProgress() {
  var currentQuestionNumber = quiz.questionIndex + 1;
  var element = document.getElementById("progress");
  element.innerHTML =
    "Question " + currentQuestionNumber + " of " + quiz.questions.length;
}

function showScores() {
  var gameOverHTML = "<h1>Result</h1>";
  gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
  var element = document.getElementById("quiz");
  element.innerHTML = gameOverHTML;
}

// create questions here
var questions = [
  new Question("How are you feeling today?", {
    "very sad": "1",
    sad: "3",
    happy: "6",
    "very happy": "9",
  }),
  new Question("How angry are you today?", {
    "very angry": "1",
    "little angry": "3",
    "not angry": "6",
    "very happy": "9",
  }),
];
// console.log(questions);
// create quiz
var quiz = new Quiz(questions);

// display quiz
populate();
<div class="grid">
  <div id="quiz">
    <h1>Self Assessment</h1>
    <hr style="margin-bottom: 20px">

    <p id="question"></p>

    <div class="buttons">
      <button id="btn0"><span id="choice0"></span></button>
      <button id="btn1"><span id="choice1"></span></button>
      <button id="btn2"><span id="choice2"></span></button>
      <button id="btn3"><span id="choice3"></span></button>
    </div>
    <hr style="margin-top: 50px">
    <footer>
      <p id="progress">Question x of y</p>
    </footer>
  </div>
</div>

ES6:

class Quiz {
  constructor(questions) {
    this.score = 0;
    this.questions = questions;
    this.questionIndex = 0;
  }

  getQuestionIndex() {
    return this.questions[this.questionIndex];
  }

  guess(answer) {
    this.score += Number(answer[1]);

    this.questionIndex++;
  }
  isEnded() {
    return this.questionIndex === this.questions.length;
  }
  populate() {
    if (quiz.isEnded()) {
      this.showScores();
    } else {
      // show question
      const element = document.getElementById("question");
      element.innerHTML = quiz.getQuestionIndex().text;

      // show options
      const question = quiz.getQuestionIndex(); /// this line
      //console.log(question)
      const choices = question.choices;
      choices.forEach((choice, i) => {
        const element = document.getElementById(`choice${i}`);
        element.innerHTML = choice[0];
        const button = document.getElementById(`btn${i}`);
        button.onclick = () => {
          this.guess(choice); /// this line
          this.populate();
        };
      });
      this.showProgress();
    }
  }

  showProgress() {
    const currentQuestionNumber = quiz.questionIndex + 1;
    const element = document.getElementById("progress");
    element.innerHTML = `Question ${currentQuestionNumber} of ${quiz.questions.length}`;
  }

  showScores() {
    let gameOverHTML = "<h1>Result</h1>";
    gameOverHTML += `<h2 id='score'> Your scores: ${quiz.score}</h2>`;
    const element = document.getElementById("quiz");
    element.innerHTML = gameOverHTML;
  }
}

class Question {
  constructor(text, choices, score, both) {
    this.text = text;
    this.choices = Object.entries(choices);
    this.both = Object.entries(choices);
  }

  isCorrectAnswer(choice) {
    return this.answer === choice;
  }
}

// create questions here
const questions = [
  new Question("How are you feeling today?", {
    "very sad": "1",
    sad: "3",
    happy: "6",
    "very happy": "9",
  }),
  new Question("How angry are you today?", {
    "very angry": "1",
    "little angry": "3",
    "not angry": "6",
    "very happy": "9",
  }),
];
// console.log(questions);
// create quiz
const quiz = new Quiz(questions);

// display quiz
quiz.populate();
<div class="grid">
  <div id="quiz">
      <h1>Self Assessment</h1>
      <hr style="margin-bottom: 20px">

      <p id="question"></p>

      <div class="buttons">
          <button id="btn0"><span id="choice0"></span></button>
          <button id="btn1"><span id="choice1"></span></button>
          <button id="btn2"><span id="choice2"></span></button>
          <button id="btn3"><span id="choice3"></span></button>
      </div>
      <hr style="margin-top: 50px">
      <footer>
          <p id="progress">Question x of y</p>
      </footer>
  </div>
</div>

【讨论】:

  • 我得到:Uncaught TypeError: Cannot read property 'choices' of undefined at Quiz.guess (questions.js:12) at HTMLButtonElement.button.onclick (questions.js:60) Line 12 is @ 987654325@
  • 我已经添加了建议阅读它.. 你这样做的方式非常复杂。尽量保持 OOP 模式
  • 感谢您的建议。我正在努力使用 Javascript。 PHP 对我来说更容易
  • 我已经添加了 ES6 版本,你可以查看第二个示例
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2012-07-23
  • 2022-06-29
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 2019-05-29
相关资源
最近更新 更多