array.find() always shows the same array - javascript
I'm currently learning JS/jQuery and thought I'd code a quiz for practice. While I managed to code the basics of the quiz I am struggling with a crucial part of my code.
In this quiz, I have an Array containing 10 objects. Each object has a question (String), options (Array), an answer (String) and a Boolean which indicates whether or not a question has been answered. Further, I filter this array to include only those elements, that haven't been asked/answered yet. However, this unansweredArr always contains 10 elements, even if I call the function again before asking the new question.
What I aim to do is the following:
Generate an array, that holds every question that hasn't been
answered yet. This is being done with
var unansweredArr = data.filter(function(question){
return question.answered === false;
});
Then I generate a random number, which will be used to grab an element out of this array. Said element then is being displayed in my HTML
When the player clicks on an option, the given answer will be checked. If correct, the player's score will be increased by 1 and the next question will be asked. Also answered: false will be set to answered: true on that specific question.
Until step 3, everything works like a charm (for me ;)) However, step 4 and further are my main problems.
Basically, step 2 and 3 should be repeated. Thus, the array should filter for every Object with answered: false. This array should update and contain 9 elements now - However, it doesn't. It still contains 10 elements and I don't know why. I tried to call the filter function again, without success. I tried refactoring some code by moving bits and pieces around, but nothing worked for me. Additionally, when checking for the right answer, it seems like the answer to the question that has been first answered is saved and will be used to for all the other questions.
Please find my code here:
var data = [{
question: "Cabrio: Check! Glas wird geext / Na klar gibt es Sex, weil ich parshippe jetzt!",
options: ["Gzuz", "Bonez MC", "RAF Camora", "LX"],
answer: "Gzuz",
answered: false
},
{
question: "Die Presse will mich mit Monsterbräuten in Bondfahrzeugen knipsen / Es ist wie Naturgewalten, weil Blitze vor dem Don erleuchten (Donner leuchten), Bitches!",
options: ["Kollegah", "Farid Bang", "Ali As", "Fatoni"],
answer: "Kollegah",
answered: false
},
{
question: "Frage: Was haben ein Rabbi, ein Priester, ein Koch mit 3 Eiern / ein Flyerverteiler mit einem Paket Flyern / ein Esel, zwei Geier, ich und 300 Freier gemeinsam? / Könnten alle dein Vadder sein!",
options: ["Snaga", "Pillath", "Torch", "KC Rebel"],
answer: "Snaga",
answered: false
},
{
question: "Denkt ihr, die Flüchtlinge sind in Partyboote gestiegen / mit dem großen Traum, im Park mit Drogen zu dealen?",
options: ["Tarek", "Maxim", "Nico", "DJ Craft"],
answer: "Tarek",
answered: false
},
{
question: "Rapper reden über Muskeln oder Brustumfang / Ich bin so ein Sklave, ich muss Benz fahren aus Gruppenzwang",
options: ["Shindy", "Bushido", "Fler", "Sido"],
answer: "Shindy",
answered: false
},
{
question: "Widerlich, Bitch! / Also glaub nicht, dass du Hund hier'n Aufreißer wirst (Hirn auf Reis servierst) wie'n China-Imbiss",
options: ["Kollegah", "Majo", "Jizi", "Gozpel"],
answer: "Kollegah",
answered: false
},
{
question: "Ich bin nicht nur der King dieser Mucke – ich bin diese Mucke!",
options: ["Kool Savas", "Eko Fresh", "Moe Mitchell", "Kaas"],
answer: "Kool Savas",
answered: false
},
{
question: "Ich brauch' Para, damit F*ckf*tzen blasen, ich muss Fixkosten tragen, die kann Rick Ross nicht zahlen.",
options: ["SSIO", "Schwester Ewa", "Xatar", "Abdi"],
answer: "SSIO",
answered: false
},
{
question: "Hater schauen und bauen sich einen Fake-Account, doch wissen, dass mein Album hitlastig ist/Hitlers Dick isst wie Eva Braun.",
options: ["Ali As", "Kollegah", "Farid Bang", "Majo"],
answer: "Ali As",
answered: false
},
{
question: "Dein Rap ist voller Tiefsinnigkeit/ Dass man als Zuhörer denkt, dein Schniedel ist klein",
options: ["SSIO", "Edgar Wasser", "Juse Ju", "Azad"],
answer: "SSIO",
answered: false
},
];
//Generate a score variable
var score = 0;
//Generate an array, which includes all the unanswered questions
var unansweredArr = data.filter(function(question) {
return question.answered === false;
});
//Random Number in order to get a random element from the array
var randomIndex = Math.floor(Math.random() * unansweredArr.length);
//Display random element/question in HTML
$("#question").text(unansweredArr[randomIndex].question);
for (var i = 0; i < 4; i++) {
$("#Option" + (i + 1)).text(unansweredArr[randomIndex].options[i]);
}
//What happens when the person answers the question
$(".Rapper").on("click", function() {
unansweredArr[randomIndex].answered = true;
var selected = $(this).text();
var trueAnswer = unansweredArr[randomIndex].answer;
//Check if answered correctly
if (auswahl === wahreAntwort) {
//Increase score by 1 and ask next question
console.log("Correct");
next();
return score = score + 1;
} else {
console.log("Wrong");
next();
return score;
}
});
function next() {
var unansweredArr = data.filter(function(question) {
return question.answered === false;
});
//Check if the array of unanswered questions is not empty
if (unansweredArr.length !== 0) {
//New random number
var randomIndex = Math.floor(Math.random() * unansweredArr.length);
//Display question and options in html
$("#question").text(unansweredArr[randomIndex].question);
for (var i = 0; i < 4; i++) {
$("#Option" + (i + 1)).text(unansweredArr[randomIndex].options[i]);
}
} else {
console.log("Game Over");
console.log(score);
}
}
/* Problems:
- unansweredArr does not update after a question has been answered.
- Answer to the first question will be the answer for the following questions.
*/
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
Zurück.
<div>
<!-- Frage Block -->
<div>
<p id="question">-- This is, where the punchline will be displayed --</p>
</div>
<!-- Antwort Möglichkeiten -->
<div>
<div>
Rapper 1
</div>
<div>
Rapper 2
</div>
<div>
Rapper 3
</div>
<div>
Rapper 4
</div>
</div>
</div>
The problem is that you define the same variables randomIndex and unansweredArr as global variables and as local variables in the function next.
When you update their value in the function next, the global variables with the same names do not change.
As a consequence you are always marking the first random question as answered:
unansweredArr[randomIndex].answered = true;
These are the global variables, and randomIndex does not reflect the most recently generated number.
Solution: remove the word var from before these variable names in the function next.
I did not check for other errors, but this one explains the behaviour you describe.
Related
Picking multiple random values from array [duplicate]
This question already has answers here: How to randomize (shuffle) a JavaScript array? (69 answers) Closed 4 months ago. Does anyone know how you can pick more than one random element from an array? The code below is a simplified version of my code, but i think it should be enough. My code picks a random quote from the array, then fills a div with the random string. But here comes my question, how do i get a new quote when userinput === quoteRandom. The code should be able to do this multiple times. let quote_array = [ 'Gresset er grønnere på andre siden av gjerdet', 'Å være sliten og nedfor og er ikke et tegn på svakhet, mest sannsynlig har du vært sterk for lenge', 'Jeg skulle ikke spise den, jeg skulle bare smake på den', 'Nøtter er ikke noe for en hel rev' ]; //Pick random quote let quoteRandom = sitat_array[Math.floor(Math.random() * sitat_array.length)]; //Fill a div with quoteRandom function fillQuote() { div.innerText = quoteRandom; } //If userinput === quoteRandom function newQuote() { fillQuote(); }
If you mutate the origanal array with sort and pop, every time you can get a random element form the rest of the array. So you will never get a quote again, only all the elements are poped, and the array is reinitialized. let quote_array = []; function getaquote() { if (quote_array.length === 0) { quote_array = [ 'Gresset er grønnere på andre siden av gjerdet', 'Å være sliten og nedfor og er ikke et tegn på svakhet, mest sannsynlig har du vært sterk for lenge', 'Jeg skulle ikke spise den, jeg skulle bare smake på den', 'Nøtter er ikke noe for en hel rev' ]; } quoteRandom1 = quote_array.sort(() => (Math.random() > .5) ? 1 : -1).pop(); console.log(quoteRandom1); } <button onclick="getaquote()">get a quote</button>
How do I change or update <p> tag data with every client request
there is my code, if(data.country_name == 'India'){ $('.fact').append("<h2 id='india'>Fact about India</h2>"); $('.fact').append("<p>The world's highest cricket ground is in Chail, Himachal Pradesh. Built in 1893 after leveling a hilltop, this cricket pitch is 2444 meters above sea level.</p>"); $(.fact).append('<p>2</p>') $(.fact).append('<p>3</p>') $(.fact).append('<p>4</p>') console.log('this a india'); } else if(data.country_name == 'Turkey'){ $('.fact').append("<h2 id='turkey'>Fact about Turkey</h2>"); $('.fact').append('<p>The story of Santa Claus originated in Turkey</p>'); }else if(data.country_name == 'Russia'){ $('.fact').append("<h2 id='russia'>Fact about Russia</h2>"); $('.fact').append('<p>Russia is home to some 20 percent of the world’s trees, and one-fifth of the world’s freshwater is in Lake Baikal.</p>'); } now, if I add 4 <p> for India's fact in the class='fact', so whenever the client location is India, it needs to show 1 random <p> from the if statement anyone can help, I make it complicated, I know it may be too simple!!
Just set up your facts as an array and use Math.random() with Math.floor() to pick a random one if(data.country_name == 'India'){ $('.fact').append("<h2 id='india'>Fact about India</h2>"); let facts = [ "The world's highest cricket ground is in Chail, Himachal Pradesh. Built in 1893 after leveling a hilltop, this cricket pitch is 2444 meters above sea level.", "fact2", "fact3", "fact4"]; $('.fact').append('<p>' + facts[Math.floor(Math.random()*facts.length)] + '</p>') console.log('this a india'); // ...
You can cut down a lot of code repetition by adding some structure to the data in an object or array and look up what you need based on data.country.name Something like: const countries = { 'India': { id: 'india', title: 'Facts about India', facts: ['I-1','I-2', 'I-3','I-4'] }, 'Turkey': { id: 'turkey', title: 'Facts about Turkey', facts: ['T-1','T-2', 'T-3','T-4'] } } const item = countries[data.country_name], fact = item.facts[Math.floor(Math.random()*item.facts.length)], $head = $('<h2>',{id: item.id, text: item.title}), $p = $('<p>',{text: fact)); $('.fact').append($head, $p);
DataTables - oLanguage.sInfo issue
I have a problem with Datatables oLanguage.sInfo. When there are more than 999 entries, the variable TOTAL is wrong. The main problem is that there is a string undefined inserted. Eg, it shows not 1 to 50 of 5,601 entries but 1 bis 50 von 5undefined601 $.extend( $.fn.dataTable.defaults, { "oLanguage": { "sInfo": "START bis END von TOTAL Einträgen", ... } }); DataTables 1.10.7 More details: http://debug.datatables.net/iqifax
I found how to fix this: "oLanguage": { "sThousands": ".",
javascript - replace from A to B [closed]
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 9 years ago. I'm trying to make a chrome extension to replace comments of known trolls in a forum by silence. is there a way to tell .replace to replace text from a startpoint to an endpoint? i.e.: replace text starting with 'Name' until 'end of post' by "" thanks in advance edit: to meet the comments: walk(document.body); function walk(node) { var child, next; switch ( node.nodeType ) { case 1: // Element case 9: // Document case 11: // Document fragment child = node.firstChild; while ( child ) { next = child.nextSibling; walk(child); child = next; } break; case 3: // Text node handleText(node); break; } } function handleText(textNode) { var v = textNode.nodeValue; var regexReplace = "Name of troll(.*)" v = v.replace(new RegExp(regexReplace), ''); textNode.nodeValue = v; } this is what the html looks like: class="up" style="padding-left: 14px" id="pid_31519766" data-pid="31519766"><div class="posting08 ch_wissenschaft"><div class="thread" style="width: 505px" id="t31519766" data-pid="31519766"><div class="row1"><div class="l" style="width:336px "><a class="offset" name="pid31519766"></a><div class="uname" style="max-width:277px "><a rel="nofollow" href="/Userprofil/ByPosting/31519766">NAME OF TROLL</a></div><div class="utools"><a rel="nofollow" class="follow" onclick="STD.FollowingRelationships.followUser(31519766,1363710557719,escape('Orakel von Silesia'))" title="Mitposter von „NAME OF TROLL” werden. „NAME OF TROLL” hat 7 Mitposter.">7</a></div></div><div class="r"><a class="std-button rate p" title="Sehr lesenswert" rel="nofollow" onclick="STD.Forum.rate('31519766',1);">+</a></div><div class="r"><a class="std-button rate n" title="Nicht lesenswert" rel="nofollow" onclick="STD.Forum.rate('31519766', 0);">-</a></div><div class="r rating"><span class="l counter n">14</span><span class="l bar"><span class="wrapper"><span class="n"></span><span class="p"></span></span></span><span class="l counter p">1</span></div><div class="clear"></div></div><div class="row2"><div class="l date" data-timestamp="11.5.2013 15:08:13"><span class="absolute">11.5.2013, 15:08</span><span class="relative"></span></div><div class="r a"><a rel="nofollow" title="Klicken Sie hier, wenn Sie auf dieses Posting antworten möchten." class="onclick" onclick="STD.Forum.post({action: 'reply', id: '31519766', trigger: this}); return false;">antworten</a></div><div class="r p"><a rel="nofollow" title="Mit diesem Link können Sie die URL des Postings aufrufen." href="/plink/1363710557719/31519766">permalink</a></div><div class="r m"><a rel="nofollow" title="Melden Sie Postings an die Redaktion, wenn diese den Community Richtlinien widersprechen." onclick="STD.Forum.report('31519766');">melden</a></div><div class="clear"></div></div></div><div class="txt" style="width: 505px"> POST I WANNA GET RID OF </p></div></div></div><div
You could use replace with a regex: General case (fiddle here): function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } var A = 'AAA'; // string A var B = 'BBB'; // string B var testStr = "BEFORE AAA WILL BE REMOVED BBB AFTER CCC BBB again DDD"; // string to be replaced var stopAtFirstBMatch = testStr.replace(new RegExp(escapeRegExp(A)+'(.*?)'+escapeRegExp(B)), ''); console.assert(stopAtFirstBMatch == "BEFORE AFTER CCC BBB again DDD"); var stopAtLastBMatch = testStr.replace(new RegExp(escapeRegExp(A)+'(.*)'+escapeRegExp(B)), ''); console.assert(stopAtLastBMatch == "BEFORE again DDD"); Your case (fiddle here): The regex Name(.*?)end of post will match anything starting from 'Name' to the first 'end of post' it finds. ((.*?) is a non-greedy match everything); In case you mean end of post is the actual end of post, you can use Name(.*) as the regex. It will match every text starting with Name. var strTest = "Hello my Name is this thal go away until the end of post problem goes away." var regexEndOfPost = "Name(.*?)end of post" // alerts: 'Hello my problem goes away' alert(strTest.replace(new RegExp(regexEndOfPost), '')); var regexNameToEnd = "Name(.*)" // in case you want from 'Name' to the end of the string console.log(strTest.replace(new RegExp(regexNameToEnd), '')); // alerts: 'Hello my ' alert(strTest.replace(new RegExp(regexNameToEnd), ''));
Function not working properly. Please help
Hello I'm having trouble with the function setUpTranslation(). //The purpose of this function is to place the French phrases into the document and set up the event handlers for the mousedown and mouseup events. //These are the arrays of the French phrases and English phrases that I have do place into the document: var english = new Array(); english[0] = "This hotel isn't far from the Eiffel Tower."; english[1] = "What time does the train arrive?"; english[2] = "We have been waiting for the bus for one half-hour."; english[3] = "This meal is delicious"; english[4] = "What day is she going to arrive?"; english[5] = "We have eleven minutes before the train leaves!"; english[6] = "Living in a foreign country is a good experience."; english[7] = "Excuse me! I'm late!"; english[8] = "Is this taxi free?"; english[9] = "Be careful when you go down the steps."; var french = new Array(); french[0] = "Cet hôtel n'est pas loin de la Tour Eiffel."; french[1] = "A quelle heure arrive le train?"; french[2] = "Nous attendons l'autobus depuis une demi-heure."; french[3] = "Ce repas est délicieux"; french[4] = "Quel jour va-t-elle arriver?"; french[5] = "Nous avons onze minutes avant le départ du train!"; french[6] = "Habiter dans un pays étranger est une bonne expérience."; french[7] = "Excusez-moi! Je suis en retard!"; french[8] = "Est-ce que ce taxi est libre?"; french[9] = "Faites attention quand vous descendez l'escalier."; //function I'm having trouble with function setUpTranslation(){ var phrases = document.getElementByTagName("p"); for (i =0; i<phrases.length; i++){ phrases[i].number =i; phrases[i].childNodes[1].innerHTML =french[i]; phrases[i].childNodes[1].onmousedown =function(){ swapFE(event); phrases[i].childNodes[1].onmouseup =function(){ swapEF(event); }; }; } //Below are the other two functions swapFE() and swapEF(). The purpose of the function swapFE() is to exchange the French phrase for the English translation //The purpose of the function swapEF() is to exchange the English translation for the French phrase. function swapFE(e){ var phrase =e.srcElement; var parent =phrase.parentNode; var idnum =parent.childNodes[0]; var phrasenum =parseInt(idnum.innerHTML)-1; phrase.innerText =english[phrasenum]; } function swapEF(e){ var phrase =e.srcElement; var parent =phrase.parentNode; var idnum =parent.childNodes[0]; var phrasenum =parseInt(idnum.innerHTML)-1; phrase.innerText =french[phrasenum]; } //Not sure if these are right. Thanks in advance!
Assuming that your HTML looks like this <p><span>1</span><span></span></p> <p><span>2</span><span></span></p> ... <p><span>10</span><span></span></p> Then all you need to do is to add the curly bracket after swapFE(event); (points for Mr Plunkett) and replace getElementByTagName with getElementsByTagName (you're missing an 's' in there). One additional thing to note: If the English phrase is shorter than the French, the container might shrink when the onmousedown event fires. If this shrinkage causes the mouse cursor to be positioned outside the container, the subsequent onmouseup event will not be triggered. Of course, if you are using block elements (e.g. a <div>) instead of my assumed <span>, that likely isn't an issue. In any case, it's probably better to attach the event listeners to the <p> tags instead.