The answer to this is probably really simple but I just can't see it.
I have an array of objects whose information I want to display in various places. I want to put each question into a section h1, of which I have five. However, the code I came up with just inserts the question of the last object in the array into every section h1, i.e., they all say "Question 5". I can't figure out why. How do I make this print each question into a different section h1?
var questions = [
{question: "Question1", choices: ["A","B","C"], answer: 0},
//etc. x 5
];
$('section h1').each(function() {
for (var i = 0; i < questions.length; i++) {
$(this).text(questions[i].question);
}
});
The .each() callback function gets passed an index as the first parameter. You can use that to determine which question to show, instead of having to loop over all of them.
So change your code to:
var questions = [
{question: "Question1", choices: ["A","B","C"], answer: 0},
//etc. x 5
];
$('section h1').each(function(index) {
$(this).text(questions[index].question);
});
EDIT: Adding additional example for how to populate the choices.
You would need to do this by looping over each section, then finding the h1 and lis within that section to populate.
Like so:
var questions = [
{question: "Question1", choices: ["A","B","C"], answer: 0},
//etc. x 5
];
$('section').each(function(index) {
var question = questions[index], $section = $(this);
$section.find('h1').text(question.question);
$section.find('li').text(function (index) {
return question.choices[index];
});
});
Related
Say I have the following array:
const myQuestions = [
{
question: ...,
...
difficulty: 2,
...
},
{
question: ...,
...
difficulty: 1
...
},
{
question: ...,
...
difficulty: 3,
...
}
etc...
];
And I want to iterate through the array in such a manner that I want to pick the first question found that has difficulty 3, which is the highest difficulty in this array.
I iterate through the array like so:
var currentcount=0;
var tempcount=currentcount;
var currentdiff=myQuestions[currentcount].difficulty;
for(tempcount;tempcount<myQuestions.length;tempcount++){
if(currentdiff<=myQuestions[tempcount].difficulty){
currentcount=tempcount;
break;
}
Once I find the next question with the matching difficulty I am looking for, I remove it from the array:
myQuestions.splice(currentcount,1)
I then want to grab the next question with the next highest difficulty, which is still 3 because it is the highest difficulty. However, there are no more questions of difficulty 3 left in the array, so the next highest difficulty is 2.
How would I be able to reuse my for-loop (or any other loop for that matter) so that it searches through the same array with the new criteria of looking for questions of difficulty 2, and so forth with questions of difficulty 1 when all the questions of difficulty 2 are exhausted?
My guess is that I would need to update currentdiff if I reach the end of the array and still haven't found anything, and then also set tempcount back to 0 at the end of the loop as well.
My best guess has been this so far, but it doesn't work as intended:
var currentcount=0;
var tempcount=currentcount;
//keeps track of the current difficulty
var currentdiff=myQuestions[currentcount].difficulty;
for(tempcount;tempcount<myQuestions.length;tempcount++){
if(currentdiff<=myQuestions[tempcount].difficulty){
currentcount=tempcount;
break; //stop the loop as the next question with the matching difficulty is found
}
else{
//overallcount is the number of questions that have been grabbed and spliced so far
//initially overallcount=0.
//if not reached the end of the array, skip the rest of the statements and start the loop again from the next iteration
if(overallcount<myQuestions.length){
continue;
}
else if(currentdiff==3){
currentdiff=2;
tempcount=0;
}
else if(currentdiff==2){
currentdiff=1;
tempcount=0;
}
else{
//if overallcount>=myQuestions.length, then the array is empty, so break the loop
break;
}
}
}
Any help would be greatly appreciated!
You could sort the questions before looping through them, like so:
let myQuestions = [{
question: '',
difficulty: 2,
},
{
question: '',
difficulty: 1,
},
{
question: '',
difficulty: 3,
},
];
myQuestions.sort(function(questionA, questionB) {
return questionB.difficulty - questionA.difficulty;
});
console.log(myQuestions);
I am trying to make a small random quizz generator, first array has the questions and they are randomly displayed (when page is loaded or when page is refreshed), the second array has the answers.
Now, when the user typed an answer, if that answer is from the answers' array is shown the correct message, even if it is not correct one for that question, and if the answer is not from the answers' array, the not correct message is shown.
I need a code to solve this (I can do it in if...else and with || and && operators, but for more than 5 entries code becomes too long and too hard to maintain)
Below javascript and html codes
//reload whole page
function refreshMe() {
window.location='index.html';
}
const myQs = [
"How many sides has a hexagon", // must always be the first answer from myRs array
"A circle has...degrees?", // must always be the second answer from myRs array
"2^3=...?",
"2+2:2=..?",
"A triangle has....degrees?",
"Square root of 2 is...?" // to be extend up to 500 entries
];
let randomItem = myQs[Math.floor(Math.random()*myQs.length)];
document.getElementById("demo").innerHTML = randomItem;
function userAnswer() {
const check = document.getElementById('answer').value;
const myRs = [
"6",
"360",
"8",
"3",
"180",
"1.41"
];
// the difference between 0 and -1?
if (myRs.indexOf(check) > -1) {
sayMessage = check + " is the correct answer!";
} else {
sayMessage = check + " is not the correct answer....";
}
document.getElementById("userA").innerHTML = sayMessage;
};
For a random question, now every answer is correct, if a answer out of myRs is typed, the message is not correct. I need a code so that the questions from myQs array to match with its own answer from myRs array, the same index in arrays, first question has first answer, and so on.
I can do it with if...else and || and && operators, but for more than 5 entries the code get too long and too hard for maintaining it.
<p> The question of the moment...</p>
<p id="demo"></p>
<button onclick="refreshMe()">Next one </button><br><br>
<input name="answer" type="text" placeholder="Your answer is....." id="answer">
<br><br>
<button onclick="userAnswer()">Check answer</button>
<p id="userA"></p>
Right now you have two lists. One contains questions, the other answers:
var questions = [ "2 + 2", "2 + 1", "1 + 1" ];
var answers = [ "4", "3", "2" ];
In order to easily check your user input, it's a good idea to convert this data structure to an object in which the question is the key, and the answer the value.
Note that this requires your question and answer combinations to be unique. I.e.: a question can not have multiple answers
var questionsWithAnswers = {
"2 + 2": "4",
// etc.
}
You can convert the data in javascript, so you don't have to rewrite the lists:
var questionsWithAnswers = {};
for (let i = 0; i < questions.length; i += 1) {
questionsWithAnswers[question[i]] = answers[i];
}
Now, your check for a question is:
var answerIsCorrect = questionsWithAnswers[question] === userInput;
I'd recommend revising the schema of your questions.
Housing questions and answers together within objects would probably be the least error prone approach.
See below for a practical example.
// Questions.
const questions = [
{q: 'How may sidea has a hexagon', a: 6},
{q: 'A circle has...degrees?', a: 360},
{q: '2^3=...?', a: 8},
{q: '2+2:2=..?', a: 3},
{q: 'A triangle has....degrees?', a: 180},
{q: 'Square root of 2 is...?', a: 1.41}
]
// Selected.
const selected = questions[Math.floor(Math.random()*questions.length)]
// Question.
const question = selected.q
document.getElementById('question').innerHTML = question
// Normalise.
const normalise = (number) => Math.round(parseFloat(number), 2)
// Submit Answer.
document.getElementById('form').addEventListener('submit', (event) => {
event.preventDefault()
const userAnswer = normalise(document.getElementById('answer').value)
const actualAnswer = normalise(selected.a)
const isCorrect = (userAnswer == actualAnswer)
document.getElementById('feedback').innerHTML = isCorrect && 'Correct 👍' || 'Incorrect 👎'
})
<div><p id="question"></p></div>
<form id="form">
<div><input id="answer" placeholder="Answer .."/></div>
<button>Submit answer</button>
</form>
<div><p id="feedback"></p><div>
First of all, you do understand that having a question and answer available in JS is not a good idea, cause user can see the code.
Anyway, I would combine questions and answer into one structure.
var QAs = [["How many sides has a hexagon", "6"],
["A circle has...degrees?", "360"]]; // and so on
let randomItem = QAs[Math.floor(Math.random()*myQs.length)];
document.getElementById("demo").innerHTML = randomItem[0];
function userAnswer() {
const check = document.getElementById('answer').value;
if (check == randomItem[1]) { // check randomItem availability in this scope. otherwise save to to window.randowItem scope.
sayMessage = check + " is the correct answer!";
} else {
sayMessage = check + " is not the correct answer....";
}
document.getElementById("userA").innerHTML = sayMessage;
}
I have a class:
class Quizer {
// construct new quiz for unique user
constructor(quizObj) {
this.quiz = quizObj;
this.currentQuestionNum = 0;
this.userSelections = [];
}
...
buttonAction(setup) {
//var text = this.quiz.question1.question; <-- //works
var text = this.quiz[currentQuestionNum].question; // doesnt work
}
}
That is constructed here:
var quiz = new Quizer(questionObjects);
Where questionObjects is:
var questionObjects = {
question1: {
question: "Darwin explained his theory of evolution in a book called?",
choices: [
"this is the correct answer, choose me!",
"On the Origin of Species",
"Survival of the Fittest"
],
correctAnswer: "On the Origin of Species"
},
question2: {
...
}
}
In buttonAction, my goal is to iterate through questionObjects and get each question. Can someone help me with the syntax?
You need something like this
for(var key in questionObjects){
// The following gives you the question for the current key
questionsObjects[key].question
}
As it is stated here:
The for...in statement iterates over the enumerable properties of an
object, in arbitrary order. For each distinct property, statements can
be executed.
This is my first time on here, so forgive me if the answer to this is obvious - but can't find a possible solution anywhere.
I'm trying to pull numbers out of a survey I want to set up, which will generate a list of cities. Thus:
var cities = array ['city1', 'city2', 'city3', 'city2', 'city4', 'city1', city2'];
Will generate a list: city1: 2, city2: 3, city3: 1, city4: 1
Is there a way to go through an array like this in Javascript? The cities will not be pre-determined - ie people could be entering anything.
Thanks in advance for any help you can give me.
tim
Like Niet already answered:
You go through the list and put the keys into a object and increment the values.
var generatedList = {};
for(var i=0;i<cities.length;i++){
if(generatedList[cities[i]]){
generatedList[cities[i]]++;
}else{
generatedList[cities[i]] = 1;
}
}
The answer is "obvious"... if you know where to start. So here's the starting line:
Create an object (literal, {})
Iterate through the array. For each item:
If the item doesn't exist as a key of the object, create the key with value 0
Increment the key on the object by 1
And... done! That's all there is to it.
This has been answered since I started this demo but this should help you understand what's happening. Open this demo with the developer console open to view the output:
http://jsfiddle.net/46wnj/
var cities = new Array('city1', 'city2', 'city3', 'city2', 'city4', 'city1', 'city2');
var citiesObject = {};
for (var x = 0; x < cities.length; x++)
{
if (citiesObject[cities[x]])
{
citiesObject[cities[x]]++
}
else
{
citiesObject[cities[x]] = 1;
}
}
I have an array that stores the values:
var array = [['favorite color'],['black','red']]
to get black I would:
document.write(array[0][1][0]);
then if i append to the array another question [['favorite thing']['box','ball']]
If I wanted ball I would:
document.write.array[1][1][1];
I am having trouble understanding arrays. I want an array with one question and multiple answers then I want to loop through them and display everything. I can do the loop but I am unsure how to find things in nested arrays once I create them.
Use a combination of objects (which work like dictionaries) and arrays. For example:
var array = [
{'question' : 'favorite color', 'choices' : ['black','red'] },
{'question' : 'favorite thing', 'choices' : ['box','ball'] }
]
for( var i = 0; i < array.length; i++ ) {
var question = array[i]['question'];
var choices = array[i]['choices'];
// here you can display / write out the questions and choices
}
Bearing in mind, creating a class and using a constructor or init methods would probably be better to encapsulate the idea of questions and answers. But the above is the basic idea.
var array = [['favorite color'],['black','red','blue']];
document.writeln(array[1][1]);
document.write(array[1][2]);
Would print red then blue see it working live : http://jsfiddle.net/HJ872/
How?
array[0] => gets an *array* = ['favorite color']
=> array[0][0] gets this first element `favorite color`
array[1] => also gets this array = ['black','red','blue']
=> and then [1][1] will get 'red', [1][2] will get `blue`