Turning If / Else conditions into for loop? - javascript

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));

Related

How to check if array is full?

Problem: I´m pushing a user input into an empty array, for my tic tac toe game.
We have 3 arrays so that it looks like the board inside the terminal.
How can I check if the board is full or if the place inside the array is taken?
I don´t know if my question makes sense, if not I will try to explain it further.
Now the code:
const prompt = require('prompt-sync')();
//Functions
function displayText(text) {
console.log(text);
}
function getUserInput() {
let userMove = prompt(displayText(MOVE_INSTRUCTION)).toUpperCase();
MOVES_MADE.push(userMove);
}
function checkUserInput(input) {
/*if(input === MOVES_MADE) {
console.log("Please enter coordinates of a free field")
}//add placeholder*/
if (input === "A1") {
GRID[0].splice(0, 1, "X"); //an Stelle A1 wird mit splice ein X eingesetzt
displayText(GRID)
} //neues Grid wird angezeigt
else if (input === "A2") {
GRID[0].splice(1, 1, "X");
displayText(GRID)
} else if (input === "A3") {
GRID[0].splice(2, 1, "X");
displayText(GRID)
} else if (input === "B1") {
GRID[1].splice(0, 1, "X");
displayText(GRID)
} else if (input === "B2") {
GRID[1].splice(1, 1, "X");
displayText(GRID)
} else if (input === "B3") {
GRID[1].splice(1, 1, "X");
displayText(GRID)
} else if (input === "C1") {
GRID[2].splice(0, 1, "X");
displayText(GRID)
} else if (input === "C2") {
GRID[2].splice(1, 1, "X");
displayText(GRID)
} else if (input === "C3") {
GRID[1].splice(2, 1, "X");
displayText(GRID)
} else {
displayText(WRONG_ENTRY)
};
}
//Variables
//Texts
const INTRO_TEXT = "What Mode would you like to play?";
const GAME_MODES = ["1. Human vs Human", "2. Random AI vs Random AI", "3. Human vs Random AI", "4. Human vs Unbeatable AI"];
const CHOOSE_MODES = "Choose by entering number in front of option.";
const GAME_MODE_TEXT = "You chose: ";
const MOVE_INSTRUCTION = "Please enter a move."
const WRONG_ENTRY = "Falsche Eingabe"
let GRID = [
[".", ".", "."],
[".", ".", "."],
[".", ".", "."]
]
let NUM_PICKED = [];
let MOVES_MADE = [];
//main
displayText(INTRO_TEXT);
displayText(GAME_MODES);
let playMode = prompt(displayText(CHOOSE_MODES));
NUM_PICKED.push(playMode);
if (Number(NUM_PICKED[0]) === 1) {
displayText(`${GAME_MODE_TEXT}: ${GAME_MODES[0]}`); //displaying text: You chose 1. Human vs Human
displayText(GRID);
getUserInput(); //asks player for a move
checkUserInput(MOVES_MADE[0]);
} else if (Number(NUM_PICKED[0]) === 2) {
displayText(`${GAME_MODE_TEXT}: ${GAME_MODES[1]}`); //displaying text: You chose 2. Random AI vs Random AI
displayText(GRID);
getUserInput(); //asks player for a move
checkUserInput(MOVES_MADE[0]);
} else if (Number(NUM_PICKED[0]) === 3) {
displayText(`${GAME_MODE_TEXT}: ${GAME_MODES[2]}`); //displaying text: You chose 3. Human vs Random AI
displayText(GRID);
getUserInput(); //asks player for a move
checkUserInput(MOVES_MADE[0]);
} else if (Number(NUM_PICKED[0]) === 4) {
displayText(`${GAME_MODE_TEXT}: ${GAME_MODES[3]}`); //displaying text: You chose 4. Human vs Unbeatable AI
displayText(GRID);
getUserInput(); //asks player for a move
checkUserInput(MOVES_MADE[0]);
} else {
displayText("WRONG ENTRY: This mode doesn't exist")
}
if (playMode === 1) {
displayText(`${GAME_MODE_TEXT}: + ${GAME_MODES[0]}`); //displaying text: You chose 1. Human vs Human
} else if (playMode === 2) {
displayText(`${GAME_MODE_TEXT}: + ${GAME_MODES[1]}`); //displaying text: You chose 2. Random AI vs Random AI
} else if (playMode === 3) {
displayText(`${GAME_MODE_TEXT}: + ${GAME_MODES[2]}`); //displaying text: You chose 3. Human vs Random AI
} else if (playMode === 4) {
displayText(`${GAME_MODE_TEXT}: + ${GAME_MODES[3]}`); //displaying text: You chose 4. Human vs Unbeatable AI
}
/*
const (DATA) = require("./date.js");
console.log("DATA");
*/
// checking if array is taken
We have our grid made out of 3 arrays, with three times . as a value that is replaced by the players input. We defined each value in the arrays to a coordinate. Now I want to check if the coordinate is already taken but before that I want to check if the board is full.
You can check any given index in your 2D array with a function like so.
// returns true if the "cell" is "empty", otherwise false
const isCellEmpty = (row, col) => GRID[row][col] === emptyCell;
And you can easily check if a 2D array contains "empty" cells using some and includes
// returns true if there are any empty "cells", otherwise false
const gridHasSpace = () => GRID.some(x => x.includes(emptyCell));
For example...
// values that represent cell states
const empty = '.';
const naught = '0';
const cross = 'X';
// returns true if the "cell" is "empty", otherwise false
const isCellEmpty = (row, col) => GRID[row][col] === empty;
// returns true if there are any empty "cells", otherwise false
const gridHasSpace = () => GRID.some(x => x.includes(empty));
const GRID = [
[empty, naught, cross],
[naught, empty, cross]
[naught, empty, cross]
]
console.log(isCellEmpty(0, 0)); // true
console.log(isCellEmpty(0, 2)); // false
console.log(gridHasSpace()); // true
what do you mean by full. You can check length of an array using array.length, in your case this would be MOVES_MADE.length.
Alternatively, you might declare a variable that increases whenever you push an element into an array and check this variable in the future. I am not sure what you are trying to achieve.
or there is another way which might solve your problem see this code if (typeof array[x]==="undefined"){ console.log("this is undefined"); }

How to randomly select array item without repeats and not have the program ask a question twice?

I am developing a trivia program, in which a user gets asked a question at random, and has to enter an answer. The program is telling the user whether they got the question right, and at the end alerts them of their score. Here is my code:
function askQuestion() {
score = 0
for (let step = 0; step < 5; step++) {
rando = Math.floor(Math.random() * 5)+1;
switch(rando) {
case 1:
var q1 = prompt("Who won the first ever international soccer World Cup? Please write the first letter in capital, and the following ones in lowercase")
if (q1 == "George Washington") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 2:
var q2 = prompt("What is a theorem in math for finding a side in a right triangle, knowing 2 others? Please write the both words in capital")
if (q2 == "Pythagorean Theorem") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 3:
var q3 = prompt("Who is the first human ever in space? Please write the full name in capital, and the following ones in lowercase")
if (q3 == "Yuri Gagarin") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 4:
var q4 = prompt("Who is the first president of the United States? Please write the full name in capital, and the following ones in lowercase")
if (q4 == "George Washington") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 5:
var q5 = prompt("In what country were the Olympics invented? Please write the first letter in capital, and the following ones in lowercase")
if (q5 == "Greece") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 6:
var q6 = prompt("What is the capital of France? Please capitalize the first letter")
if (q6 == "France") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 7:
var q7 = prompt("What is the most purchased video game of all time? Please capitalize the first letter")
if (q7 == "Minecraft") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 8:
var q8 = prompt("What is the most watched television brodcast ever? Please write the full name, capitlizing the abbreviation of the organization it is created by, and then the name too.")
if (q8 == "UEFA Euro 2020") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 9:
var q9 = prompt("What is the most popular board game in the world? Please capitalize")
if (q9 == "Chess") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
case 10:
var q10 = prompt("What year was the U.S. Declaration of Independence written and ratified?")
if (q10 == "1776") {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
break;
default:
alert("This is impossible")
break;
}
}
alert("Thanks for playing! Your score is " + score + " out of 5!")
}
askQuestion()
I am unable to find a way to not have the program ask a question twice using an array. May someone please help me? Thank you.
Here's a hint, ditch the switch. Have an array of objects with all the questions and answers, like:
const data: [
{ question: "Who?", answer: "Him" },
{ question: "What?", answer: "That" },
{ question: "Where?", answer: "There" }
]
Ditch the for loop, use a while loop, and reuse the logic. All you need is the random index
while ( data.length > 0 ) {
let randomIndex = Math.floor(Math.random() * data.length) + 1;
var userAnswer = prompt(data[randomIndex].question)
if (userAnswer === data[randomIndex].answer) {
alert("Correct!")
score = score + 1
} else {
alert("Sorry you are incorrect")
}
data.splice(randomIndex, 1); // remove that question and answer set
}
You could create an array of all of your questions paired with their answers like here in the example below.
Important: define these questions outside of your askQuestions function as you only want them defined once when the page loads.
const questions = [
{
question: 'Who won the first ever international soccer World Cup? Please write the first letter in capital, and the following ones in lowercase',
answer: 'george washington'
},
{
question: 'What is a theorem in math for finding a side in a right triangle, knowing 2 others? Please write the both words in capital',
answer: 'pythagorean theorem'
},
{
...
},
...
];
Then select a random question from the array. This is done similar to your current method.
const randomIndex = Math.floor(Math.random() * questions.length);
const randomQuestion = questions[randomIndex];
From here you can access both the question and answer properties that are in the question object. You can apply the same logic as you already did to ask the question and to check the answer.
Now if an answer is correct, then you don't want to ask that question again. You can do this by removing the question form our questions array after a good answer has been given.
With the .splice method on the question array we can remove a single item from the array based on an index. We already got the index stored in randomIndex and we'll need it to remove the question from the array.
The question cannot be asked again until the page has been refreshed.
const answer = prompt(randomQuestion.question);
if (answer.toLowerCase() === randomQuestion.answer) {
score++;
// Remove 1 item starting from the randomIndex value.
questions.splice(randomIndex, 1);
alert('Correct!');
} else {
alert('Incorrect!')
}
As an addition I would suggest that you define your answers all in lowercase and transform the answer of the user also to lowercase and then compare them. You can do this with the .toLowerCase() method on the string that prompt returns.

NodeJS - Sorting Like Rock Paper Scissors - Dynamic Number Of Players

I'm working on a game that has a sort of rock paper scissors system, only more complicated, using "values" such as 3 rock beats 2 rock, where one player can choose the amount of rocks he wants to use in one turn. This game can/has to handle more than 2 players, but 2 players is also possible. I was only able to do that with values, using this code:
array.push({ "player": player, "score": parseInt(cardInformation.value), "Seat": i, element: cardInformation.element});
array.sort(function (a, b) {
return b.score - a.score;
});
var rank = 1;
var lastWinner = -1;
for (var i = 0; i < array.length; i++) {
if (i > 0 && array[i].score < array[i - 1].score) {
rank++;
}
array[i].rank = rank;
array[i].winStatus = loss;
if(rank == 1) {
if(lastWinner != -1) {
array[lastWinner].winStatus = tie;
array[i].winStatus = tie;
} else
array[i].winStatus = win;
lastWinner = i;
}
}
I've looked all over for a system like rock paper scissors but all I could find was for 2 players and I'm unsure how to make it more. Please help me if you have the time.
Hope this helps :
const TURN_INTERVAL = 10//seconds
const GAME_STATE = {
status:1, // 1:player action is allowed / 0:player action is frozen
turnData:{ // temp storage for playerIDs grouped by value chosen
1:[], //paper
2:[], //scissors
3:[] //rock
},
versus:{ //what kills what
1:3,
2:1,
3:2
}
}
function GlobalTurn(){
console.log('[Round]','started')
GAME_STATE.status = 0; // players must wait for turn end response
for(var i=1; i<4;i++){ // notify each group of how many they killed
var thisGroupKills = GAME_STATE.versus[i]; //which is the weak group against this one
var totalKilled = GAME_STATE.turnData[thisGroupKills].length //how much this group has killed
console.log('group',i,'killed a total of',totalKilled) //send to clients instead
/* Here you can iterate over each playerID if you need to :
for(var j=0; j<GAME_STATE.turnData[i].length){
console.log('player',GAME_STATE.turnData[i],'killed a total of',totalKilled)
}
*/
}
EndTurn()
}
function EndTurn(){
console.log('Next round will start in',TURN_INTERVAL,'seconds')
GAME_STATE.turnData = {1:[],2:[],3:[]} //reset for next round
GAME_STATE.status = 1; // players can send actions (their pick)
setTimeout(GlobalTurn,TURN_INTERVAL*1000); //prepare next round calculator
}

Shortest way to compare your score to three ranges in jQuery

I have the following code:
function display_message() {
var low = data.result[0].max; //returns 30
var medium = data.result[1].max; // returns 60
var high = data.result[2].max; // returns 100
// mypoints are 67 for example
if(mypoints > low) {
if(mypoints > medium) {
alert('You got a high score');
} else {
alert('You got a medium score');
}
} else {
alert('You got a low score');
}
}
This code works fine. I compare my average score to the standard low / medium / high score.
Low score: 0-30 points
Medium score: 31-60 points
High score: 61-100 points
My question though is how to make my code a bit prettier? I am not sure if the code is considered as clear and efficient.
Any opinions would be much appreciated, thank you
There is no need for the if else with low, just check from smallest to highest.
if (mypoints <= low) {
//low msg
} else if (mypoints <= medium) {
//medium msg
} else {
//high msg
}
or you can go the opposite direction and check for the highest first with greater than
You could use a condition without nested conditions.
if (mypoints > medium) {
alert('You got a high score');
} else if (mypoints > low) {
alert('You got a medium score');
} else {
alert('You got a low score');
}
Here, we iterate over the various values that make up the score range. The loop will iterate over each score range in turn, meaning you need to have the lowest score first and highest score last. We then save score name against myscore to be alerted out at a later point.
This approach allows for expandability - you can add as many score ranges in the middle without having to add any more if/else blocks.
let data = {result: [{max: 30}, {max: 60}, {max: 100}]},
mypoints = 67;
function display_message() {
let score_range = {
low: data.result[0].max, //returns 30
medium: data.result[1].max, // returns 60
high: data.result[2].max // returns 100
},
myscore = 'fail';
for (var score in score_range) {
if (score_range.hasOwnProperty(score)) {
if (mypoints > score_range[score]) {
myscore = score;
}
}
}
alert('You got a ' + myscore + ' score!');
}
display_message();
You could store the messages in an array, and find the correct index like so:
function display_message() {
var low = 30,
medium = 60,
rank;
mypoints = 67; // for example
rank = ['low', 'medium', 'high'][+(mypoints > low) + +(mypoints > medium)];
console.log('You got a ' + rank + ' score');
}
display_message();
The magic is in the unary plus operator which converts booleans returned by comparisons to 0 or 1 accordingly. It's also easy to include more rankings if needed.
mypoints < low ? alert("you get low score") : (mypoints < medium ? alert("you get medium score") : alert("you get high score"))
You can use the switch statement
function display_message() {
var low = data.result[0].max; //returns 30
var medium = data.result[1].max; // returns 60
var high = data.result[2].max; // returns 100
switch (true) {
case mypoints > medium:
alert('You got a high score');
break;
case mypoints > low:
alert('You got a medium score');
break;
default:
alert('You got a low score');
}
}
You can create a function which takes the score and an array as an argument with the different levels and their names {"score": 30, "text": "You got a low score"} and then just loop that and output what is closest to what you sent in and return the matching text.
Example:
var myScore = 50,
scoreIntervals = [{
"score": 30,
"text": "Low score"
},{
"score": 60,
"text": "Average score"
},{
"score": 100,
"text": "High score"
}];
function evaluateScore(score, scoreIntervals) {
var output = scoreIntervals[scoreIntervals.length - 1].text;
$.each(scoreIntervals, function(key, val) {
if(score <= val.score) {
output = val.text;
return false;
}
});
return output;
}
console.log(evaluateScore(myScore, scoreIntervals));

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