The purpose of the code is to allow users to play the game as many times as they want. I keep on getting stuck in infinite loop and I am not sure why. P.s. I need to stick to switch statements.
var color1 = prompt('Pick a color');
while (true){
switch (color1) {
case (color1 = 'blue'):
document.write("nope");
break;
case (color1 = 'yellow'):
document.write("nope");
break;
case (color1 = 'white'):
document.write("nope");
break;
case (color1 = 'gray'):
document.write("nope");
break;
case (color1 = 'green'):
document.write("yes");
break;
case (color1 = 'pink'):
document.write("nope");
break;
case(color1 = 'purple'):
document.write("nope");
break;
case (color1 = 'orange'):
document.write("nope");
break;
case (color1 = 'green'):
document.write("nope");
break;
case (color1 = 'magenta'):
document.write("nope");
break;
case (color1 = 'red'):
document.write("nope");
break;
}
if(color1 = false)
alert('Thanks')
}
There are several problems in your code:
The = operator does assignment, you need === or == for comparison.
You are not using case correctly within your switch: you need to just put the value you want to match against color1, don't try to do a comparison as if it were an if condition. So you need something like:
switch (color1) {
case 'red':
document.write("nope");
break;
It doesn't make sense to list a whole bunch of different incorrect colours in different cases, because even aside from the fact that the user might enter values not in your list, really the logic should be "Is it green?" yes/no. An if statement would make much more sense than a switch, but since you've said you have to use switch then you should have one case for the correct answer and then use default to catch all other values:
switch (color1) {
case 'green':
document.write("yes");
break;
default:
document.write("nope");
break;
}
Or in a hypothetical case where you legitimately needed to list several values but have them do the same thing you should make use of a "fall through" like this:
switch (color1) {
case 'blue':
case 'yellow':
case 'white':
document.write("nope");
break;
case 'green':
document.write("yes");
break;
}
The final if needs to break out of the while loop when the condition is true - currently all it does is show an alert, hence the infinite loop.
Testing if (color1 === false) (after fixing the operator) doesn't make sense, because color1 won't ever be false: if the user clicks the Cancel button on the prompt() then the value will be null, so test for that. You could also test for an empty string. Except you can move that logic into a case instead of having an if after the switch statement. Instead of while(true), use while(!finished) and add a finished variable that you set to true when the user clicks the Cancel button.
The prompt() needs to be inside the loop, otherwise the user will only be prompted once before the loop starts and the loop will keep repeating testing the same value over and over.
Using document.write() isn't a good plan, but I'm declaring that issue out of scope for this question. In the meantime, you should at least output <p> elements or something so that each "nope" and "yes" appears on its own line.
Putting that all together:
var finished = false;
while (!finished) {
var color1 = prompt('Pick a color');
switch (color1) {
case null:
case '':
alert('Thanks');
finished = true;
break;
case 'green':
document.write("<p>yes</p>");
break;
default:
document.write("<p>nope</p>");
break;
}
}
Related
I am creating a recycling app and am attempting to use a switch statement to provide the user with instructions on what to do with the item upon entering into an input field. I'm a little turned around on how to call it (I am very new to switch). Eventually I want to have a few different arrays according to material. How would I place the item's within an array in the a switch? Would I be better off with if else statements? Any advice would be much appreciated!
const plasticItem = ["Milk Jug , Shampoo, Deodarant, Soda Bottle"];
function recycleItem(plasticItem) {
let instructions = "";
switch (true) {
case plasticItem:
instructions = "Put in recycling";
break;
}
}
I made this code which should work:
function recycleItem(){
const x = document.querySelector("input").value;
switch(x) {
case "Milk Jug":
console.log("Milk");
break;
case "Shampoo":
// code block
console.log("Shampoo");
break;
case "Deodarant":
console.log("Deodarant");
break
case "Soda Bottle":
console.log("Soda Bottle");
break
default:
// code block
}
}
Can someone help me understand, why is my switch case returning the default value. Even when I change all values it only returns the default at first I thought it was a hoisting issue in my code but after debugging it's I found it's the statement, it ignores all other cases. (p.s please don't be mean I just want to understand, the other examples I've seen aren't simply explained and don't have much up votes so I did try.)
var shippingMethod = document.querySelector("[name=r_method]:checked").value;
var shippingChoice;
switch(shippingMethod) {
case "usps":
shippingChoice = 2;
break;
case "ups":
shippingChoice = 3;
break;
default:
shippingChoice = 0;
break;
}
console.log(shippingChoice);
I would suggest adding an if statement to verify there is a value for shippingMethod. As well, when querying for the value, make sure to include quote ("") around the value of the name.
var shippingMethod = "default";
var shippingChoice;
if (document.querySelector('[name="r_method"]:checked') != null)
{
shippingMethod = document.querySelector('[name="r_method"]:checked').value;
}
switch(shippingMethod) {
case "usps":
shippingChoice = 2;
break;
case "ups":
shippingChoice = 3;
break;
default:
shippingChoice = 0;
break;
}
console.log(shippingChoice);
I'm working on a Freecodecamp problem and one component is taking the value of 5 cards, comparing it to a value you assign, and then presenting the current count based upon those cards.
So for example;
Cards with numbers 2,3,4,5 and 6 should incrememnt the count by 1.
Cards with numbers 7,8 and 9 should do nothing.
Cards 10, J, Q, K, A should decrement the count by 1.
So if I give it 5 card values, it should add them up and provide me with the count, based upon those card values.
Here is my code (I know it's sloppy, but trying to get it better);
var count = 0;
function cc(card) {
// Only change code below this line
switch (card) {
case ("A"):
--count; }
switch (card) {
case ("2"):
++count; }
switch (card) {
case ("3"):
++count; }
switch (card) {
case ("4"):
++count; }
switch (card) {
case ("5"):
++count; }
switch (card) {
case ("6"):
++count; }
switch (card) {
case ("7"):
}
switch (card) {
case ("8"):
}
switch (card) {
case ("9"):
}
switch (card) {
case ("10"):
--count; }
switch (card) {
case ("J"):
--count; }
switch (card) {
case ("Q"):
--count; }
switch (card) {
case ("K"):
--count; }
return count;
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
Now I've tried using return count; return ++count; and return --count; which all give me different values. I think I might not be referencing the values of cc at the bottom to even pick up a count based on the correct values, I think I may just be issuing blind counts for the whole set of cards.
Any help is super appreciated. Thanks in advance.
Something like this:
var count = 0;
function cc(card) {//or, with ES6: cc = (card) => { (no 'function' keyword required)
switch (card) {
case ("A")://all of these 'fall through' until they hit break...be careful with this, and comment it in your code
case ("10"):
case ("J"):
case ("Q"):
case ("K"):
count -= 1;//or, count = count - 1
break;//break sends you out of the switch statement
case ("2")://same here
case ("3"):
case ("4"):
case ("5"):
case ("6"):
count += 1;
break;
//no need to do anything with 7, 8, 9
}
return count;
}
You can also add a "default" for the end in case a value other than the handled ones is sent, but in this case all you'd be doing would be count = count, which isn't necessary. Good luck!
See how to use switch,case:
https://www.w3schools.com/js/js_switch.asp
Using switch-case is quite different from using if-else which I think you are mimicking.
I have a switch statement which has several cases. These cases compare values and assign a text to a variable. But when I try to execute this switch, it always executes the default case. But my condition is true.. Why?
Here is my value
Apartment
Here is my code
var rental_cat = $('#rentals_type').val();
alert(rental_cat);
var rental_type = "";
switch (rental_cat) {
case (rental_cat == "Apartment"):
rental_type='daily';
alert(rental_type);
break;
case (rental_cat == "Office"):
rental_type='work_daily';
alert(rental_type);
break;
default:
rental_type='other';
alert(rental_type);
break;
}
When I execute this switch, it always gives me "other"
Remove the conditional expression inside the "case" clause.
Try this:
var rental_cat = $('#rentals_type').val();
alert(rental_cat);
var rental_type = "";
switch (rental_cat) {
case "Apartment":
rental_type='daily';
alert(rental_type);
break;
case "Office":
rental_type='work_daily';
alert(rental_type);
break;
default:
rental_type='other';
alert(rental_type);
break;
}
switch (rental_cat) {
case (rental_cat == "Apartment"):
is equivalent to
switch (rental_cat) {
case true:
which in turn is equivalent to
if (rental_cat === true)
You don't put a condition in the case, the condition is created as an equality check between the switch and the cases, so it should be like this instead:
switch (rental_cat) {
case "Apartment":
a switch is not the right structure to deal with this problem. Here I'd recommend a map:
var rentalTypesByCat = {
DEFAULT: "other",
"Apartement": "daily",
"Office": "work_daily",
}
var rental_cat = $('#rentals_type').val();
console.log("rental_cat:", rental_cat);
var rental_type = rentalTypesByCat[rental_cat] || rentalTypesByCat.DEFAULT;
console.log("rental_type:", rental_type);
or if you need it a bit more explicit (for example because some of your mapped values may be falsy themselves):
var rental_type = rentalTypesByCat[rental_cat in rentalTypesByCat? rental_cat: "DEFAULT"];
console.log("rental_type:", rental_type);
I am working on a custom gallery right now, but I cannot seem to get the array of variables to apply during the loop. What am I missing?
Here is the relevant code:
var racerImage = ['$("img.ryanthumb")', '$("img.pierthumb")', '$("img.jeremythumb")',
'$("img.mattthumb")', '$("img.andrewthumb")', '$("img.alanthumb")',
'$("img.kevinthumb")', '$("img.mikethumb")', '$("img.dougthumb")'];
var showMe= ['showRacer("ryan")\;', 'showRacer("pier")\;',
'showRacer("jeremy")\;', 'showRacer("matt")\;', 'showRacer("andrew")\;',
'showRacer("alan")\;', 'showRacer("kevin")\;', 'showRacer("mike")\;',
'showRacer("doug")\;'];
for (var i = 0; i < racerImage.length; i++)
{
racerImage[i].click(function(){
switch (i)
{
case 0:
showMe[i];
break;
case 1:
showMe[i];
break;
case 2:
showMe[i];
break;
case 3:
showMe[i];
break;
case 4:
showMe[i];
break;
case 5:
showMe[i];
break;
case 6:
showMe[i];
break;
case 7:
showMe[i];
break;
case 8:
showMe[i];
break;
}
});
}
Basically I am trying to use a for loop to apply the jquery multiple times instead of writing it over and over again. I don't know if I am going about this the right way, but any insights would be great. Thanks again!
You ended up having three main problems:
You have jQuery code strings in the racerImage array which end up being just strings, not actual jQuery objects so they don't work.
You have function call code strings in the showMe array which don't work either.
Your value of i in the click handler function doesn't work because the event handler happens some time later when the value of i is no longer what you want it to be.
To fix those, change the racerImage array to just an array of selectors and turn them into jQuery objects when needed in your code.
Change the showMe array into an array of names that you can just pass to the showRacer() function when needed.
And, you don't need the switch statement at all since i is already your index.
var racerImage = ["img.ryanthumb", img.pierthumb, "img.jeremythumb",
"img.mattthumb", "img.andrewthumb" /* and so on */];
var showMe= ["ryan", "pier", "jeremy", "matt" /* and so on */];
for (var i = 0; i < racerImage.length; i++) {
// create closure to capture the value of i so it is available during the event handler
(function(i) {
$(racerImage[i]).click(function(){
showRacer(showMe[i]);
});
})(i);
}
racerImage[0] is still just a string which contains the value $("img.ryanthumb") - it is not the jQuery object.
What you probably want to do is put the selector value in the string, and then call the jQuery function from there:
var racerImage = ['img.ryanthumb', 'img.pierthumb', ...etc...];
...
$(racerImage[i]).click(function(){...});
Or you can have your array be the jQuery objects and use them:
var racerImage = [$("img.ryanthumb"), $("img.pierthumb"), ...etc...];
...
racerImage[i].click(function(){...});
EDIT
Thanks Joel for the comment - yep, same problem on showRacer - maybe those can be an array of functions:
var showMe= [function(){showRacer("ryan");}, function(){showRacer("pier");}, ...etc...];
...
showMe[i]();
I would do this instead:
var racer = ['ryan', 'pier', 'jeremy', 'matt', 'andrew', 'alan', 'kevin', 'mike', 'doug'];
$.each(racer, function(i, v){
$('img.'+v+'thumb').click(function(){
showRacer(v);
})
});