Simple quiz with javascript - javascript

I am trying to make a simple quiz system only using javascript and HTML with no external libraries. But I ran into some problems. The script is giving the wrong solution. Even when I select the right checkboxes it only outputs 1 correct answer. I don't know what exactly am I doing wrong, or if there's an alternative way for doing this.
<div class="quizsection">
<button onclick="startQuiz()" id="startQuiz">Start Quiz</button>
<div id="questions"></div>
</div>
<script>
//Create Array with questions and solutions
var allQuestions = [{
question: "Before Mt. Everest was discovered, whaich mountain was considered to be the highest mountain in the world?",
choices: ["Mt. Kilimanjaro", "Kanchenjunga", "Mount Everest"],
correctAnswer: 1
},
{
question: "Does England have a 4th of July?",
choices: ["Yes", "No", "I don't know"],
correctAnswer: 0
},
{
question: "What is Rupert the bear's middle name?",
choices: ["Bear", "He doesn't have one!", "The", "Rupert"],
correctAnswer: 2
},
{
question: " What can you never eat for breakfast? ",
choices: ["Dinner", "Something sugary", "Lunch", "Supper"],
correctAnswer: 0
},
{
question: "If there are three apples and you took two away, how many do you have?",
choices: ["One", "Two", "None"],
correctAnswer: 1
},
{
question: "Spell 'Silk' out loud, 3 times in a row. What do cows drink?",
choices: ["Milk", "Water", "Juice", "Cows can't drink"],
correctAnswer: 1
},
{
question: "Which is heavier, 100 pounds of rocks or 100 pounds of gold? ",
choices: ["100 pounds of rocks", "100 pounds of rocks", "They weigh the same"],
correctAnswer: 2
},
{
question: "Can you spell 80 in two letters?",
choices: ["AI-TY", "It's not possible", "EIGH-TY", "A-T"],
correctAnswer: 3
},
{
question: "What question must always be answered ''Yes''?",
choices: ["What does Y-E-S spell?", "Will everyone die someday?", "Does everyone have a biological mother?", "Are you a human?"],
correctAnswer: 0
},
{
question: "How many sides does a circle have?",
choices: ["The back", "None. It's a circle", "Two", "Four"],
correctAnswer: 2
},
{
question: "What has a tail but no body?",
choices: ["A human", "A coin", "A cloud"],
correctAnswer: 1
},
{
question: "What word in the English language is always spelled incorrectly?",
choices: ["It's possible to spell anything right as long as you learn it", "Shakespeare", "Onomatopoeia", "Incorrectly"],
correctAnswer: 3
},
{
question: "When do you stop at green and go at red?",
choices: ["Watermelon!", "Traffic light!", "Garden"],
correctAnswer: 0
},
{
question: "What rotates but still remains in the same place?",
choices: ["Bottle (spin the bottle game)", "Clock", "Stairs"],
correctAnswer: 2
},
{
question: "How can you lift an elephant with one hand?",
choices: ["Truck", "Use both hands!", "Use a lever", "There is no such thing"],
correctAnswer: 3
}
];
//Function to start the quiz
function startQuiz(){
var i;
var j;
var k;
for(i=0; i<allQuestions.length; i++){
document.getElementById("questions").innerHTML +='<form id="question">Q'+(i+1)+': '+ allQuestions[i].question;
for(j=0; j<allQuestions[i].choices.length; j++){
document.forms[i].innerHTML += '</div><div class="answer"><input name="q1" value="'+ allQuestions[i].choices[j] +'" id="value4" type="checkbox" />' + allQuestions[i].choices[j] + '<br/>';
}
document.getElementById("questions").innerHTML +='</form><br/><br/>';
}
document.getElementById("questions").innerHTML += '<button onclick="solveQuiz()">Solve Quiz</button>';
}
function solveQuiz(){
var x;
var txt = ' ';
var i = 0;
var correct = 0;
for(i = 0; i < document.forms[i].length;i++) {
x = document.forms[i];
if(x[i].checked) {
correctAnswer = allQuestions[i].correctAnswer;
if(x[i].value == allQuestions[i].choices[correctAnswer]){
correct += 1;
}
}
}
document.getElementById("questions").innerHTML += 'Correct answers: ' + correct;
}
</script>

function solveQuiz(){
var x;
var txt = ' ';
var i = 0;
var correct = 0;
for(i = 0; i < document.forms.length;i++) {
x = document.forms[i];
for(j = 0; j<x.length; j++){
if(x[j].checked) {
correctAnswer = allQuestions[i].correctAnswer;
if(x[j].value == allQuestions[i].choices[correctAnswer]){
correct += 1;
}
}
}
}
document.getElementById("questions").innerHTML += 'Correct answers: '+ correct;
}
you can replace your solveQuiz fn with above block;
Its better to use radio instead of checkbox;
document.forms[i].innerHTML += '</div><div class="answer"><input name="q1" value="'+ allQuestions[i].choices[j] +'" id="value4" type="radio" />' + allQuestions[i].choices[j] + '<br/>';

In your function startQuiz you generate more form with same id and also input inside has always the same id for all questions. Try to concatenate id of these elements with for counter index.

Related

Turning If / Else conditions into for loop?

New developer currently taking courses, working on a trivia game project with Javascript & Jquery. I have a long if else condition, looking to see if I can put in a for loop to condense the code. or if there is any other method to shorten it? I have 8 total questions for the game.
if (question1 == "Red Hot Chili Peppers") {
userCorrect ++;
}else {
userIncorrect ++;
}
if (question2 == "Rage Against The Machine") {
userCorrect ++;
}else {
userIncorrect ++;
}
if (question3 == "Nirvana") {
userCorrect ++;
}else {
userIncorrect ++;
}
if (question4 == "Sublime") {
userCorrect ++;
}else {
userIncorrect ++;
}
if (question5 == "The Black Keys") {
userCorrect ++;
}else {
userIncorrect ++;
}
if (question6 == "Dave Grohl") {
userCorrect ++;
}else {
userIncorrect ++;
}
if (question7 == "Pearl Jam") {
userCorrect ++;
}else {
userIncorrect ++;
}
if (question8 == "Big Gigantic") {
userCorrect ++;
}else {
userIncorrect ++;
}
}
The game works; however, looking to condense this down if possible.
Use an array of correct answers (and an array of questions) instead:
const correctAnswers = [
"Red Hot Chili Peppers",
"Rage Against The Machine",
"Nirvana"
// ...
];
// ...
// have userAnswers be an array of answers
const userCorrect = correctAnswers
.filter((correctAnswer, i) => userAnswers[i] === correctAnswer)
.length;
const userIncorrect = correctAnswers.length - userCorrect;
If you're familiar with reduce, you can remove the need for a .length check at the end, reduce is a bit more appropriate for transforming an array into a single expression:
const userCorrect = correctAnswers
.reduce((a, correctAnswer, i) => a + userAnswers[i] === correctAnswer, 0)
If you save que correct answers on an array and the user responses on another where the array indexes matchs answers with responses, you can use a loop to compare they and count the correct ones.
const answers = [
"Red Hot Chili Peppers",
"Rage Against The Machine",
"Nirvana",
"Sublime",
"The Black Keys",
"Dave Grohl",
"Pearl Jam",
"Big Gigantic"
];
let userResponses = [
"Red Hot Chili Peppers",
"Pink Floyd",
"Nirvana",
"Sublime",
"The Black Keys",
"Bob Marley",
"Pearl Jam",
"Artic Monkeys"
];
let goods = 0;
userResponses.forEach((x, idx) =>
{
goods += (x === answers[idx]);
});
console.log("Corrects: " + goods);
console.log("Incorrects: " + (answers.length - goods));
Store the correct answers in one array and the user's guesses in another. Then, loop over the correct answers and check it against the corresponding answer from the user's guesses array.
This can be implemented in a few different ways, but since you are just learning, I'm keeping it pretty simple. It relies on the first array being looped over with .forEach() and then uses a ternary operator to decide if the score should be increased.
const correctAnswers = [
"Red Hot Chili Peppers",
"Rage Against The Machine",
"Nirvana"
];
let userAnswers = [
"Red Hot Chili Peppers",
"Green Day",
"Nirvana"
];
let numberCorrect = 0;
// Loop over the right answers
correctAnswers.forEach(function(answer, index){
// Increment the score if the user's answer matches the correct answer.
numberCorrect = userAnswers[index] === answer ? numberCorrect + 1 : numberCorrect;
});
console.log("You got " + numberCorrect + " out of " + correctAnswers.length + " correct.");
Start by creating an array of correct answers. Then, store all of the user's answers in a different array. Initialize the correctCount counter to 0 and use a simple for loop to loop through the list, comparing each value to the other. Also, since the incorectCount can be easily calculated, you don't have to count it separately.
const correctAnswers = [
"Red Hot Chili Peppers",
"Rage Against The Machine",
"Nirvana",
"Sublime"
];
const userAnswers = [
"Red Hot Chili Peppers",
"Rage Against The Machine",
"Nirvana",
"Metallica"
];
let correctCount = 0;
for (let i = 0; i < correctAnswers.length; i++) {
if (correctAnswers[i] === userAnswers[i]) {
correctCount++;
}
}
console.log("Correct answers:" + correctCount);
console.log("Incorrect answers:" + (correctAnswers.length - correctCount));

Why is new RegEx not working properly

For some reason…
When ever I try to get the Object.keys from replace.letters and use the Object.keys in a new RegExp joined by |…
The new RegExp only recognize some of the Object.keys but not all of them. I need the RegEx to dynamically create itself.
If I place a static RegExp in… It works perfectly fine.
Demo does not work properly
Demo works perfectly but I have to force the Regex to know what to look for
replace = {
letters: {
a: {
after: ["til"]
},
b: {
because: ["bec"]
},
c: {
cool: ["chill"]
},
e: {
energy: ["en"]
},
h: {
light: ["look"]
},
i: {
keen: ["ok"]
},
r: {
roll: ["rock"]
},
s: {
ship: ["skip"]
},
t: {
trip: ["tip"]
}
}
}
sentence = [
"If you want a cookie, eat your dinner.",
"As soon as you enter the house, change clean your room and mop the floor.",
"So long as I'm king, I will ensure your safty.",
"Change the curtains, after house is painted.",
"Change the curtains, by the time that we are headed.",
"Assuming that you are a good person, hold my beer.",
"Reject the offer, even if I'm not there.",
"Reject the offer, zoom I'm not there.",
"By the time the bus gets here, the show will be over with.",
"Choose a random number.",
"Try not to mess this, that and those up.",
"Change a random number, pick a color, and put it in jason's house.",
"Zoom, fix and lower the bar.",
"Don't change the house.",
"Create a playground.",
"While you were gone, I changed the lockes",
"Before I stop the car, can you get my wallet."
]
let objects_letters = Object.keys(replace.letters).join('|')
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'gi')
console.log(letters_RegEx)//This isn't working properly.
for (var i = 0; i < sentence.length; i++) {
let $this = sentence[i]
let commaKey = /,/g.test($this)
let if_While_Key = /^(If|While)/gi.test($this)
//Here is the problem
let letterKey = letters_RegEx.test($this)
//Here is the problem
if (commaKey) {
if (if_While_Key) {}
if (letterKey) {
$('body').append($this + '<br>');
} else {}
} else {}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
replace = {
letters: {
a: {
after: ["til"]
},
b: {
because: ["bec"]
},
c: {
cool: ["chill"]
},
e: {
energy: ["en"]
},
h: {
light: ["look"]
},
i: {
keen: ["ok"]
},
r: {
roll: ["rock"]
},
s: {
ship: ["skip"]
},
t: {
trip: ["tip"]
}
}
}
sentence = [
"If you want a cookie, eat your dinner.",
"As soon as you enter the house, change clean your room and mop the floor.",
"So long as I'm king, I will ensure your safty.",
"Change the curtains, after house is painted.",
"Change the curtains, by the time that we are headed.",
"Assuming that you are a good person, hold my beer.",
"Reject the offer, even if I'm not there.",
"Reject the offer, zoom I'm not there.",
"By the time the bus gets here, the show will be over with.",
"Choose a random number.",
"Try not to mess this, that and those up.",
"Change a random number, pick a color, and put it in jason's house.",
"Zoom, fix and lower the bar.",
"Don't change the house.",
"Create a playground.",
"While you were gone, I changed the lockes",
"Before I stop the car, can you get my wallet."
]
let objects_letters = Object.keys(replace.letters).join('|')
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'gi')
console.log(letters_RegEx)//This isn't working properly.
for (var i = 0; i < sentence.length; i++) {
let $this = sentence[i]
let commaKey = /,/g.test($this)
let if_While_Key = /^(If|While)/gi.test($this)
//Here is the problem
let letterKey = /^(a|b|c|e|h|i|r|s|t)/gi.test($this)
//Here is the problem
if (commaKey) {
if (if_While_Key) {}
if (letterKey) {
$('body').append($this + '<br>');
} else {}
} else {}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your problem is your RegExp Flags
Change
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'gi')
to
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'i')
replace = {
letters: {
a: {
after: ["til"]
},
b: {
because: ["bec"]
},
c: {
cool: ["chill"]
},
e: {
energy: ["en"]
},
h: {
light: ["look"]
},
i: {
keen: ["ok"]
},
r: {
roll: ["rock"]
},
s: {
ship: ["skip"]
},
t: {
trip: ["tip"]
}
}
}
sentence = [
"If you want a cookie, eat your dinner.",
"As soon as you enter the house, change clean your room and mop the floor.",
"So long as I'm king, I will ensure your safty.",
"Change the curtains, after house is painted.",
"Change the curtains, by the time that we are headed.",
"Assuming that you are a good person, hold my beer.",
"Reject the offer, even if I'm not there.",
"Reject the offer, zoom I'm not there.",
"By the time the bus gets here, the show will be over with.",
"Choose a random number.",
"Try not to mess this, that and those up.",
"Change a random number, pick a color, and put it in jason's house.",
"Zoom, fix and lower the bar.",
"Don't change the house.",
"Create a playground.",
"While you were gone, I changed the lockes",
"Before I stop the car, can you get my wallet."
]
let objects_letters = Object.keys(replace.letters).join('|')
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'i')
console.log(letters_RegEx)//This isn't working properly.
for (var i = 0; i < sentence.length; i++) {
let $this = sentence[i]
let commaKey = /,/g.test($this)
let if_While_Key = /^(If|While)/gi.test($this)
//Here is the problem
let letterKey = letters_RegEx.test($this)
//Here is the problem
if (commaKey) {
if (if_While_Key) {}
if (letterKey) {
$('body').append($this + '<br>');
} else {}
} else {}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have to precede special characters with \ when included in a string (RegExp).
EDIT: it looks like you need to escape all the special characters in regexp. I have borrowed escapeRegExp function from Mathias Bynens
Please see corrected snippet below:
replace = {
letters: {
a: {
after: ["til"]
},
b: {
because: ["bec"]
},
c: {
cool: ["chill"]
},
e: {
energy: ["en"]
},
h: {
light: ["look"]
},
i: {
keen: ["ok"]
},
r: {
roll: ["rock"]
},
s: {
ship: ["skip"]
},
t: {
trip: ["tip"]
}
}
}
sentence = [
"If you want a cookie, eat your dinner.",
"As soon as you enter the house, change clean your room and mop the floor.",
"So long as I'm king, I will ensure your safty.",
"Change the curtains, after house is painted.",
"Change the curtains, by the time that we are headed.",
"Assuming that you are a good person, hold my beer.",
"Reject the offer, even if I'm not there.",
"Reject the offer, zoom I'm not there.",
"By the time the bus gets here, the show will be over with.",
"Choose a random number.",
"Try not to mess this, that and those up.",
"Change a random number, pick a color, and put it in jason's house.",
"Zoom, fix and lower the bar.",
"Don't change the house.",
"Create a playground.",
"While you were gone, I changed the lockes",
"Before I stop the car, can you get my wallet."
]
let objects_letters = Object.keys(replace.letters).join('\|')
let letters_RegEx = new RegExp(escapeRegExp('^(' + objects_letters + ')'), 'i')
console.log(letters_RegEx);
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\$&');
}
for (var i = 0; i < sentence.length; i++) {
let $this = sentence[i]
let commaKey = /,/g.test($this)
let if_While_Key = /^(If|While)/gi.test($this)
//FIXED
let letterKey = letters_RegEx.exec($this)
if (commaKey) {
if (if_While_Key) {}
if (letterKey) {
$('body').append($this + '<br>');
} else {}
} else {}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Alerting data specifics inside array

I'm running into a javascript beginner's problem. I have this data stored in an array, and I'm trying to alert the data to see if it checks out.
I want to alert myself the average of the distance of all, not both planets even though both is all in this case, but I eventually want to have an array that keeps a lot more than just two. Right now, it just alerts the distance of the last record in the array list, which is weird. I thought it'd be an average for all.
Also, how do I program the least and highest numbers of the "Distance" property in the array, and then alert the "Host name" with it. So, if I have a button and I click on "Closest", the Host name of the lowest number in "Distance [pc]" will be alerted. I only need an example of the code for "Distance", so I'll know how to do the same for all other variables.
Thank you if you're willing to help out!
Btw, the list is JSON data. Maybe important to mention this.
// this array holds the json data, in this case stastics of exoplanets retrieved from nasa's website
var arr= [ {
"rowid": 684,
"Host name": "K2-15",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.221,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 437,
"Effective Temperature [K]": 5131,
"Date of Last Update": "7/16/2015"
},
{
"rowid": 687,
"Host name": "K2-17",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.199,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 134,
"Effective Temperature [K]": 4320,
"Date of Last Update": "7/16/2015"
}];
//every record is put in a variable
var rowid;
var hostName;
var numberOfPlanetsInSystem;
var planetMass;
var planetRadius;
var distance;
var effectiveTemperature;
for(var i=0;i<arr.length;i++){
rowid= arr[i]["rowid"];
hostName= arr[i]["Host name"];
numberOfPlanetsInSystem= arr[i]["Number of Planets in System"];
planetMass= arr[i]["Planet Mass or M*sin(i)[Jupiter mass]"];
planetRadius= arr[i]["Planet Radius [Jupiter radii]"];
distance= arr[i]["Distance [pc]"];
effectiveTemperature= arr[i]["Effective Temperature [K]"];
};
//alert to test it out
alert(distance);
let totalDistance = maxDistance = 0;
let minDistance = arr[0]["Distance [pc]"];
let closestHost = farthestHost = "";
for(let i = 0; i < arr.length; i ++) {
totalDistance += arr[i]["Distance [pc]"]
if (arr[i]["Distance [pc]"] < minDistance) {
minDistance = arr[i]["Distance [pc]"];
closestHost = arr[i]["Host name"];
}
if (arr[i]["Distance [pc]"] > maxDistance) {
maxDistance = arr[i]["Distance [pc]"];
farthestHost = arr[i]["Host name"];
}
}
let meanDistance = totalDistance/arr.length;
In your cycle you are always overwrite your variable distance, not adding them.
Use distance += arr[i]["Distance [pc]"]
+= measn distance = distance + arr[i]["Distance [pc]"]
EDIT
Here is a working jsFiddle
You need to init var distance = 0;
var distance = 0; //Important!
var arr = [{
"rowid": 684,
"Host name": "K2-15",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.221,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 437,
"Effective Temperature [K]": 5131,
"Date of Last Update": "7/16/2015"
},
{
"rowid": 687,
"Host name": "K2-17",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.199,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 134,
"Effective Temperature [K]": 4320,
"Date of Last Update": "7/16/2015"
}];
for (var i = 0; i < arr.length; i++) {
distance += arr[i]["Distance [pc]"];
};
alert('Total distance: ' + distance + "\n" + 'Number of planets: ' + arr.length + "\n" + 'Average: ' + distance / arr.length);

javascript/node JSON parsing issue

Here is my example data:
http://api.setlist.fm/rest/0.1/setlist/4bf763f6.json
I'm just writing a node app that prints out the details of this page. What I'm concerned with are sets, set and song.
var sets = setlist.sets
res.write(JSON.stringify(sets)) // THIS SHOWS THE CORRECT DATA
var numSets = Object.keys(sets).length;
for(var i = 0; i < numSets; i++){
res.write("\nsets " + i);
var set = sets.set[i];
console.log(Object.getOwnPropertyNames(set))
var numSet = Object.keys(set).length;
res.write(JSON.stringify(set))
for(var j = 0; j < numSet; j++){
res.write("\nset " + (j+1) + " of " + numSet);
var song = set.song;
console.log(Object.getOwnPropertyNames(song))
numSong = Object.keys(song).length;
for(var k = 0; k < numSong; k++){
res.write("\n song " + j + "-" + k);
res.write("\n "+JSON.stringify(song[k]["#name"]));
}
}
}
what I get is:
set 1 of 1
song 0-0
"Lift Me Up"
song 0-1
"Hard to See"
song 0-2
"Never Enough"
song 0-3
"Got Your Six"
song 0-4
"Bad Company"
song 0-5
"Jekyll and Hyde"
song 0-6
"Drum Solo"
song 0-7
"Burn MF"
song 0-8
"Wrong Side of Heaven"
song 0-9
"Battle Born"
song 0-10
"Coming Down"
song 0-11
"Here to Die"
There are TWO song elements in set: (sorry no code block or it won't wrap)
{
"set": [{
"song": [{
"#name": "Lift Me Up"
}, {
"#name": "Hard to See"
}, {
"#name": "Never Enough"
}, {
"#name": "Got Your Six"
}, {
"#name": "Bad Company",
"cover": {
"#disambiguation": "British blues-rock supergroup",
"#mbid": "0053dbd9-bfbc-4e38-9f08-66a27d914c38",
"#name": "Bad Company",
"#sortName": "Bad Company",
"#tmid": "734487",
"url": "http://www.setlist.fm/setlists/bad-company-3bd6b8b0.html"
}
}, {
"#name": "Jekyll and Hyde"
}, {
"#name": "Drum Solo"
}, {
"#name": "Burn MF"
}, {
"#name": "Wrong Side of Heaven",
"info": "Acoustic"
}, {
"#name": "Battle Born",
"info": "Acoustic and Electric"
}, {
"#name": "Coming Down"
}, {
"#name": "Here to Die"
}]
}, {
"#encore": "1",
"song": [{
"#name": "Under and Over It"
}, {
"#name": "Burn It Down"
}, {
"#name": "The Bleeding"
}]
}]
}
In Swift I just make set a Dictionary and it works just fine. Javascript is not my forte. Why can't I get that second song element?
setlist.set is an array of two objects, one containing the "regular"(?) songs and the other containing the encore information.
It looks like you are mixing up loop variables with other objects/arrays and not iterating what you think you're iterating.
Here's a simplified version that should show what you're expecting:
// `sets` is an object containing (at least) `set` and `url` properties
var sets = setlist.sets;
// `set` is an array containing (in your example, two) objects
var set = sets.set;
for (var i = 0; i < set.length; ++i) {
console.log('Set %d/%d', i+1, set.length);
// `curSet` is an object containing a `song` property
var curSet = set[i];
// `songs` is an array of objects
var songs = curSet.song;
for (var j = 0; j < songs.length; ++j) {
// `song` is an object containing properties like `#name` and possibly others
var song = songs[j];
console.log(' - Song: %s', song['#name']);
}
}
The line
var numSets = Object.keys(sets).length;
Should be
var numSets = sets.set.length;
May I also suggest that you use a forEach loop rather than a for loop (a .map() would be even better). for loops are much more prone to bugs than the alternatives.

First Javascript program. What am I doing wrong?

I have finally gotten around to creating my first little practice program in Javascript. I know it's not elegant as it could be. I have gotten most of this code to work, but I still get an "undefined" string when I run it a few times. I don't know why. Would someone be kind enough to explain to me where this undefined is coming from?
var work = new Array();
work[1] = "product design";
work[2] = "product system design";
work[3] = "product social media post x5";
work[4] = "product Agent Recruitment system design";
work[5] = "product profile system design";
work[6] = "product Agent testing design";
work[7] = "product customer support";
work[8] = "product promotion";
var course = new Array();
course[1] = "javascript";
course[2] = "mandarin";
course[3] = "javascript practical-Code Academy";
course[4] = "javascript practical-learn Street";
course[5] = "mandarin practical-memrise";
course[6] = "new stuff with audiobooks";
var activity = new Array();
activity[1] = "listen to podcasts";
activity[2] = "chat online";
activity[3] = "Exercise";
activity[4] = "take a walk";
activity[5] = "call a friend";
var picker1 = Math.floor(Math.random()*3+1);
var picker2 = Math.floor(Math.random()*work.length+1);
var picker3 = Math.floor(Math.random()*course.length+1);
var picker4 = Math.floor(Math.random()*activity.length+1);
var group_pick = function(){
if(picker1 === 1){
return "Time to work on ";
} else if(picker1 === 2){
return "Time to learn some ";
} else if (picker1 === 3){
return "Lets relax and ";
} else {
return "error in group_pick";
}
};
var item_pick = function() {
if (picker1 === 1) {
return work[picker2] ;
} else if (picker1 === 2) {
return course [picker3] ;
} else if (picker1 === 3) {
return activity[picker4] ;
} else {
return "error in item_pick";
}
};
var task = group_pick() + item_pick();
document.write(task);
Array's start with an index of zero. When you assign a value to the 1 index, a 0 index is created you, with no value (undefined).
var arr = new Array();
arr[1] = 'hi!';
console.log(arr); // [undefined, "hi!"]
console.log(arr.length) // 2
Length is 2, check that out. You thought you had one item in that array but length is 2.
Usually it's easier to not manage the array indices yourself. And the array literal syntax is usually preferred for a number of reasons.
var arr = [];
arr.push('hi!');
console.log(arr); // ["hi!"]
console.log(arr.length) // 1
Or just create the array with the items in it directly, very handy.
var arr = [
"hi",
"there!"
];
console.log(arr); // ["hi", "there"]
console.log(arr.length) // 2
Once you are making the arrays properly, you can get a random item with simply:
var arr = ['a','b','c'];
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]); // "a", "b" or possibly "c"
This works because var index will be calculated by a random value of between 0.0 and up to but not including 1.0 times 3 (the length of the array). Which can give you a 0, 1 or a 2.
So this arr right here, has 3 items, one at 0, one at 1, and one at 2.
Learning to address arrays from zero can be mentally tricky. You sort of get used to it. Eventually.
A working example using these tips here: http://jsfiddle.net/du5Jb/
I changed how the arrays are declared, and removed the unneeded +1 from var pickerX calculations.
The problem is that the .length attribute for arrays counts the number of elements in the array starting from zero. So for example activity has elements 1 through 5, so according to Javascript the .length is actually 6. Then your random number calculation will choose a number from 1 through 7, past the end of the array. This is where the undefined comes from.
You can fix this by starting your index numbering at 0 instead of 1, so activity would have elements 0 through 4, with a .length of 5. Also remove the +1 from your choice calculations.
When you use your "pickers", you don't want to have the +1 inside of the `Math.floor functions.
Consider this array:
var array = [ "one", "two", "three" ];
array.length; // 3
The length is 3 -- makes sense, there are 3 items inside.
But arrays are zero-based.
array[0]; // "one"
array[1]; // "two"
array[2]; // "three"
array[3]; // undefined
So when you add that + 1, you're:
a) making it impossible to pick the first thing in the array
b) making it possible to pick a number that is exactly 1 higher than the last element in the array (undefined)
The problem here as i see it is that when you generate your random variables you're doing PickerX + 1...
So the right way to do it would be PickerX without the +1.
Also Off topic you shouldn't use if commands, try using switch case...
Here's the fixed code-
var work = new Array()
work[0] = "product design";
work[1] = "product system design";
work[2] = "product social media post x5";
work[3] = "product Agent Recruitment system design";
work[4] = "product profile system design";
work[5] = "product Agent testing design";
work[6] = "product customer support";
work[7] = "product promotion";
var course = new Array();
course[0] = "javascript";
course[1] = "mandarin";
course[2] = "javascript practical-Code Academy";
course[3] = "javascript practical-learn Street";
course[4] = "mandarin practical-memrise";
course[5] = "new stuff with audiobooks";
var activity = new Array();
activity[0] = "listen to podcasts";
activity[1] = "chat online";
activity[2] = "Exercise";
activity[3] = "take a walk";
activity[4] = "call a friend";
var picker1 = Math.floor(Math.random() * 3 +1 );
var picker2 = Math.floor(Math.random() * work.length );
var picker3 = Math.floor(Math.random() * course.length );
var picker4 = Math.floor(Math.random() * activity.length );
var group_pick = function(){
switch(picker1){
case 1:
return "Time to work on ";
case 2:
return "Time to learn some ";
case 3:
return "Lets relax and ";
default:
return "error in group_pick";
}
};
var item_pick = function() {
switch(picker1){
case 1:
return work[picker2] ;
case 2:
return course [picker3] ;
case 3:
return activity[picker4] ;
default:
return "error in item_pick";
}
};
var task = group_pick() + item_pick();
document.write( task );​
Don't work so hard. Zero is your friend. Let's go golfing...
var work = [
"product design", "product system design",
"product social media post x5",
"product Agent Recruitment system design",
"product profile system design",
"product Agent testing design",
"product customer support", "product promotion",
], course = [
"javascript", "mandarin",
"javascript practical-Code Academy",
"javascript practical-learn Street",
"mandarin practical-memrise", "new stuff with audiobooks",
], activity = [
"listen to podcasts", "chat online", "Exercise",
"take a walk", "call a friend",
];
function rint(cap) {
return (Math.random() * cap) | 0;
}
function pick(item) {
switch (item) {
case 0: return "Time to work on " +
work[ rint(work.length) ];
case 1: return "Time to learn some " +
course[ rint(course.length) ];
case 2: return "Lets relax and " +
activity[ rint(activity.length) ];
default: return "error";
}
}
document.write(pick(rint(3)) + '<br>');

Categories

Resources