简体   繁体   中英

Create new objects inside of a function with JavaScript?

So I want to create a function that if, if a question is answered wrong, it stores the wrong answer into a new object? So that I can list all of the wrong answers at the end?

var answerList = [{question:1, answer:1},{question:2, answer:2},]
var listofWrongAnswers = [];

if (answerSelected != answerlist[1].answer) {
    /* create a new object
       put answerlist[1].question and answerlist[i].answer in new object and push to 
       array ListofWrongAnswers */
}

I dont get how you can randomly name variables? if that's even possible.

Couldn't you simply create a new object based on the current question?

Something like this should work:

if (answerSelected != answerlist[1].answer) {

    listofWrongAnswers.push({question: answerlist[1].question, answer: answerlist[1].answer});
}

However, you should look to make that index a parameter:

function addToWrongAnswers(answerSelected, idx) {

    if (answerSelected != answerlist[idx].answer) {

        listofWrongAnswers.push({question: answerlist[idx].question, answer: answerlist[idx].answer});
    }
}

I assume you want something like this:

function getQuestion(number){
    for(var i = 0; i < answerList.length; i++){
        if(answerList[i].question === number){
            return answerList[i];
        }
    }
}

function checkAnswer(questionNumber, answer){
    var question = getQuestion(questionNumber);
    if(answer !== question.answer){
        listofWrongAnswers[question];
    }
}

However , I'm also assuming you'll start with Question 1 and increment the number, so it would be even simpler if you just selected the question using an array index, rather than iterating through it. So this might be better:

var answerList = [{question:1, answer:1}, {question:2, answer:2}];
var listofWrongAnswers = [];

function checkAnswer(questionNumber, answer){
    var question = answerList[questionNumber - 1];
    if(answer !== question.answer){
        listofWrongAnswers[question];
    }
}

If you want to clone that question object and push it into that array, you can use

listofWrongAnswer.push({question: answerlist[1].question, answer: answerlist[1].answer});

But with this code you won't can use == operator to compare question objects existing at those arrays

listofWrongAnswer[1] == answerlist[1] // It's false

But if you don't want such a behavior you can store only references to question objects in the wrong answer list:

listofWrongAnswer.push(answerlist[1]);

With this code you can compare question objects with == operator

listofWrongAnswer[1] == answerlist[1] // It's true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM