is there a way to create a switch comparator like this one?
switch (item) {
case (item<= 10):
money += 25;
$('#money').html(money);
break;
case (item > 10 && item <= 20):
money += 50;
$('#money').html(money);
break;
}
may be this:
item = YourValue;
switch (true) {
case (item <= 10):
money += 25;
$('#money').html(money);
break;
case (item > 10 && item <= 20):
money += 50;
$('#money').html(money);
break;
}
The expressions in the case statements will evaluate to true or false, and if that matches the switch condition,
but as per my suggestion you should go with if...else if...else statement for this kind of business logic.
Simple answer: No. Switch..case statements don't work like this. You would need an if & else if statement:
if (item <= 10)
{
money += 25;
$('#money').html(money);
}
else if (item > 10 && item <= 20)
{
money += 50;
$('#money').html(money);
}
You can use the if else instead of switch
if (item <= 10)
{
money += 25;
$('#money').html(money);
}
else if (item > 10 && item <= 20)
{
money += 50;
$('#money').html(money);
}
Related
Am I writing the correct switch case with conditions?
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
alert('31');
break;
default:
alert('>41');
}
For some reason, the alert does not occur when the conditions are matched!
A switch works by comparing what is in switch() to every case.
switch (cnt) {
case 1: ....
case 2: ....
case 3: ....
}
works like:
if (cnt === 1) ...
if (cnt === 2) ...
if (cnt === 3) ...
Therefore, you can't have any logic in the case statements.
switch (cnt) {
case (cnt >= 10 && cnt <= 20): ...
}
works like
if (cnt === (cnt >= 10 && cnt <= 20)) ...
and that's just nonsense. :)
Use if () { } else if () { } else { } instead.
You should not use switch for this scenario. This is the proper approach:
var cnt = $("#div1 p").length;
alert(cnt);
if (cnt >= 10 && cnt <= 20)
{
alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
alert('31');
}
else
{
alert('>41');
}
This should work with this :
var cnt = $("#div1 p").length;
switch (true) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
break;
default:
alert('>41');
}
Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.
Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.
$('.next').click(function(){
var imageToSlide = $('#imageSprite'); // Get id of image
switch(true) {
case (imageToSlide.hasClass('pos1')):
imageToSlide.removeClass('pos1').addClass('pos2');
break;
case (imageToSlide.hasClass('pos2')):
imageToSlide.removeClass('pos2').addClass('pos3');
break;
case (imageToSlide.hasClass('pos3')):
imageToSlide.removeClass('pos3').addClass('pos4');
break;
case (imageToSlide.hasClass('pos4')):
imageToSlide.removeClass('pos4').addClass('pos1');
}
}); `
What you are doing is to look for (0) or (1) results.
(cnt >= 10 && cnt <= 20) returns either true or false.
--edit--
you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length.
--edit--
function date_conversion(start_date){
var formattedDate = new Date(start_date);
var d = formattedDate.getDate();
var m = formattedDate.getMonth();
var month;
m += 1; // JavaScript months are 0-11
switch (m) {
case 1: {
month="Jan";
break;
}
case 2: {
month="Feb";
break;
}
case 3: {
month="Mar";
break;
}
case 4: {
month="Apr";
break;
}
case 5: {
month="May";
break;
}
case 6: {
month="Jun";
break;
}
case 7: {
month="Jul";
break;
}
case 8: {
month="Aug";
break;
}
case 9: {
month="Sep";
break;
}
case 10: {
month="Oct";
break;
}
case 11: {
month="Nov";
break;
}
case 12: {
month="Dec";
break;
}
}
var y = formattedDate.getFullYear();
var now_date=d + "-" + month + "-" + y;
return now_date;
}
Switch case is every help full instead of if else statement :
switch ($("[id*=btnSave]").val()) {
case 'Search':
saveFlight();
break;
case 'Update':
break;
case 'Delete':
break;
default:
break;
}
Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.
What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.
Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.
Like follow:
switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
alert('10');
break;
case (cnt >= 21 && cnt <= 30 && cnt):
alert('21');
break;
case (cnt >= 31 && cnt <= 40 && cnt):
alert('31');
break;
default:
alert('>41');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>
Please tell me what is wrong with my code. It seems like after continue; it still loops over the same block even if I use the largest number as an input. Here it still wants me to input a larger number:
// 1) Generate a random integer from 0 to 10 (reference: Math.random())
const RanNum = Math.floor(Math.random() * Math.floor(11))
console.log(RanNum)
// 2) Ask the user input (reference: prompt())
let userInput = prompt(`Give me a number`)
const userInputInt = parseInt(userInput)
console.log(userInput)
console.log(typeof(userInput))
console.log(userInputInt)
console.log(typeof(userInputInt))
if(isNaN(userInput)){
prompt(`Give me a freaking number`)
}else{
let x = 0;
while (x < 4) {
console.log('hi')
console.log(userInputInt)
console.log(RanNum)
if (userInputInt == RanNum) {
console.log(`win`)
prompt('YOU GOT IT MAN')
break;
}
else if (userInputInt < RanNum) {
x = x+1 ;
prompt('Larger please')
continue;
}
else if (userInputInt > RanNum) {
x= x+1
prompt('Smaller please')
continue;
}
}
if(x > 3){alert('More than 3 times')}
}
However, this one works fine. Can someone point to me what's wrong?
// Guess the number
const randomNumber = Math.floor(Math.random() * 11);
let trials = 0;
while(trials < 4){
const guess= parseInt(prompt("Give me a number(0-10)!"));
if(isNaN(guess)){
alert("You are not inputing a number");
// Works for while-loop, for-loop, do-while loop
continue;
}
trials++;
if(guess === randomNumber){
// Equal
alert("You win!!");
// If the player wins, terminate the game
// Works for while-loop, for-loop, do-while loop
break;
}else{
// Unequal
if(guess > randomNumber){
alert("Too large!");
}else{
alert("Too small");
}
}
}
if(trials > 3){
alert("You loses");
}
You can use switch-case except if-else:
let i = 0,
solution = Math.floor(Math.random() * Math.floor(11)),
max_tries = 3;
while (nmb !== solution && i < max_tries + 1) {
if (i < max_tries) {
var nmb = Number(prompt("Put number (1 - 10): "));
switch(true) {
case nmb > solution : console.log("Smaller please"); break;
case nmb < solution : console.log("Largest please"); break;
default : console.log("YOU GOT IT MAN");
}
}
else { console.log("You lose! Number was: " + solution) }
i++
}
You only need to add outputs to the console as in your variant.
I'm working on switch statements at the moment, and have a little function below that turn a given numerical score into a grade. Or at least that's what it's supposed to do, but somehow it all goes wrong, and I'm not sure why!
function convertScoreToGrade(score) {
var grade = "";
switch(score) {
case 100>=score && score>=90: grade = "A";
break;
case 89>=score && score>=80: grade = "B";
break;
case 79>=score && score>=70: grade = "C";
break;
case 69>=score && score>=60: grade = "D";
break;
case 59>=score && score>=0: grade = "F";
break;
case score>100 || score<0: grade = "INVALID SCORE";
} return grade;
}
convertScoreToGrade(10);
For example, when I input the number 10 I only get an empty string, which suggests that the relevant case isn't evaluated. Any help would be appreciated.
Based on your example, here is a modification to make your code work
The big take away here is you match the parameter you pass into the switch statement. So passing a boolean value of true means that if your condition is true, that will be the case.
IMO, a switch statement is what you should use for this case. It's a small amount of cases (5), and is very readable for anyone who will work on or maintain this code at a later point.
function convertScoreToGrade(score) {
// Check for invalid scores first
if(typeof score !== 'number' || score < 0 || score > 100)
return "INVALID SCORE";
var grade = "";
// Pass a boolean value, remember we are matching this value
// EX: (score < 90) is true when score is 0 - 89
switch(true) {
case score < 60:
grade = "F";
break;
case score < 70:
grade = "D";
break;
case score < 80:
grade = "C";
break;
case score < 90:
grade = "B";
break;
case score <= 100:
grade = "A";
break;
}
// If you want partial grades
if(score % 10 <= 3 && score !== 100 )
grade += "-";
else if(score % 10 >= 7 || score == 100)
grade += "+";
return grade;
}
// These are small test cases to show you
// that convertScoreToGrade works as defined
console.log(convertScoreToGrade(-1));
console.log(convertScoreToGrade(101));
console.log(convertScoreToGrade('The dog ate it.'));
var i = 50;
while(i <= 100){
console.log(i, 'should be', convertScoreToGrade(i));
i += 4;
}
Bad solution that you might think of that is clearly worse than the alternative but I already typed it and I think it's helpful for you to understand that this is how you'd handle it with if statements. Please have mercy on me for posting such lousy code.
function convertScoreToGrade(score) {
var grade = "";
if(score>=0){
grade = "F";
}
if(score>=60){
grade = "D";
}
if(score>=70){
grade = "C";
}
if(score>=80){
grade = "B";
}
if(score>=90){
grade = "A";
}
if (score>100 || score<0){
grade = "INVALID SCORE";
}
return grade;
}
convertScoreToGrade(10);
function convertScoreToGrade(score) {
// scores is an array of objects
// Each element in the scores array has two properties, grade and score
// grade is the letter grade, score is the minimum score to achieve that grade
var i,l,scores = [{ grade: 'A', score: 90},
{grade: 'B',score : 80},
{grade: 'C',score: 70},
{grade: 'D',score: 60 }];
// Ensure score is between 0 and 100 inclusive
if (score < 0 || score > 100) {
return 'Invalid';
}
// Loop through all the scores and exit when the score is larger than the minimum
l = scores.length;
for (i=0;i<l;i++) {
if (score >= scores[i].score) {
return scores[i].grade;
}
}
// If the score was not found, the grade is an F
return 'F';
}
console.log(convertScoreToGrade(82));
console.log(convertScoreToGrade(90));
console.log(convertScoreToGrade(50));
This question already has answers here:
Expression inside switch case statement
(8 answers)
Closed 8 years ago.
The evaluations in the console print in the second line seem correct, but the switch statement won't work. And I am not getting any errors.
for (var i = 0; i < 100; i++) {
console.log(i % 3 === 0, i % 5 === 0);
switch (i) {
case i % 3 === 0:
console.log(i, " by three");
break;
case i % 5 === 0:
console.log(i, " by five ");
break;
}
}
http://jsfiddle.net/vL4omdxs/
As the comment said, that's not how you use switch/case.
You evaluate the condition in switch, then create different behaviours using cases.
Here is your code slightly modified (actually not so slightly, there's a small math twist):
var res = document.getElementById('r');
for (var i = 0; i < 100; i++) {
//console.log(i % 3 === 0, i % 5 === 0);
switch (i % 15) {
case 0:
r.innerHTML += i + " by three and five<br>";
break;
case 3:
case 6:
case 9:
case 12:
r.innerHTML += i + " by three<br>";
break;
case 5:
case 10:
r.innerHTML += i + " by five<br>";
break;
}
}
<div id="r"></div>
Just a hint (offtopic, but might help): switch/case is not the best approach for the 3/5 problem. See how much simpler it looks using ifs:
var res = document.getElementById('r');
for (var i = 0; i < 100; i++) {
res.innerHTML += "<br>" + i + ": ";
if (i % 3 == 0) {
res.innerHTML += "by three ";
}
if (i % 5 == 0) {
res.innerHTML += "by five ";
}
}
<div id="r"></div>
Case expressions are tested for strict equality so you need to change the switch from switch (1) to switch (true). However note that only one of the case blocks will be executed.
That's not the way to do the switch statement. It must be:
switch (i % 3) {
case 0:
...
break;
case 1:
...
break;
}
The expression within switch brackets is compared with the expression after case keyword. Take your code as example:
for (var i = 0; i < 100; i++) {
console.log(i % 3 === 0, i % 5 === 0);
switch (i) {
case i % 3 === 0: // if (i) equals (i % 3 === 0), run this branch
console.log(i, " by three");
break;
case i % 5 === 0: // if (i) equals (i % 5 === 0), run this branch
console.log(i, " by five ");
break;
}
}
And please remember, "equal" here means ===. Since your case expressions all return boolean, they'll never be equal to your i, which is a number.
I'm writing swtich javascript switch statement in JS file and figured out the problem whole day still cannot find the solution.
Here is my javascript file written in jQuery :
var percent = 20;
var widthbytes;
switch(percent)
{
case 0:
widthbytes=0;
break;
case (percent > 10 && percent < 20):
widthbytes=16;
break;
case (percent >=20 && percent < 30):
widthbytes=30;
break;
default:
widthbytes=0;
break;
}
average.width(widthbytes);
It always return to default instead of 30. Anything wrong with my codes ?
switch statement only check the value of variable and then give the result according to that value so your expression
case (percent > 10 && percent < 20):
return boolean value which is not not comparable to variable value. Use if-else to get the job done.
just make a bit change in your code.
You have switch(percent)**in your code, only change for this ***switch(true)*.
The reason for that is because the switch statement return a boolean value, this is why we need they have the same comparation, i.e. boolean vrs boolean.
For example the case 10: return one value; true or false.
I can't see a problems with #Carlos Marin's answer. This works:-
var percent = 10; //test values-> 10, 11, 19, 20, 21, 29, 30
var widthbytes;
switch(true){
// case 0:
// widthbytes=0;
// break;
case (percent > 10 && percent < 20):
widthbytes=16;
break;
case (percent >=20 && percent < 30):
widthbytes=30;
break;
default:
widthbytes=0;
break;
}
console.log(widthbytes);
switch statements don't work like that. Your second case is checked like this: if (percent == (percent > 10 && percent < 20)) ..., which will not yield the desired result.
You could use an if / elseif / else construct:
if (percent === 0) {
widthbytes = 0;
} else if (percent > 10 && percent < 20 {
widthbytes = 16;
} else if (percent >= 20 && percent < 30 {
widthbytes = 30;
} else {
widthbytes = 0;
}
Or you could use a function that turns the ranges into constants:
function getRange(percent) {
return Math.floor(percent/10);
}
switch(getRange(percent)) {
case 10:
widthbytes = 16;
break;
case 20:
widthbytes = 30;
break;
default:
widthbytes = 0;
}
Note that to get a cleaner implementation i assimilated your original case 0: into the default, since they both do the same thing. If that is not desirable, you need to change the getRange function to no longer return the same range for 0 as for any number between 0 and 10.