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.
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>
I am trying to write a function that satisfies the following:
-count from 1 to 100,
-on numbers divisible with 4 print “byfour”,
-on numbers divisible with 6 print “bysix”,
-on numbers divisible with both 4 and 6 print “byfoursix”,
-skip numbers divisible with 7,
-on the number 32 add '!'.
This is what I have, but I was wondering if there is way to use the switch statement, or any more optimal way to write it.
function maths(){
for (let i=1; i<=100; i++){
if (i === 32){
console.log (`${i}!`);
}
else if (i % 4 === 0 && i % 6 === 0){
console.log ("byfoursix");
}
else if (i % 4 ===0) {
console.log ("byfour");
}
else if (i % 6 === 0) {
console.log ("bysix");
}
else if (i % 7 === 0){
continue;
}
else {
console.log (i);
}
}
}
maths();
Any input or advice is super appreciated! Thank you
It is possible to use a switch case if you wanted to by setting the switch parameter to true so that it runs, although it's not necessarily a better way to write it.
for (let i = 1; i <= 100; i++) {
switch (true) {
case (i === 32):
console.log(`${i}!`);
break;
case (i % 4 === 0 && i % 6 === 0):
console.log('byfoursix');
break;
case (i % 4 === 0):
console.log('byfour');
break;
case (i % 6 === 0):
console.log('bysix');
break;
case (i % 7 === 0):
break;
default:
console.log(i);
}
}
This question already has answers here:
javascript fizzbuzz switch statement
(8 answers)
Closed 4 years ago.
Can't seem to point out something obvious. This solution doesn't work. Please help?
FizzBuzz question: Print numbers from 1 to 100. Print Fizz instead of numbers divisible by 3. Print Buzz instead of numbers divisible by 5. Print FizzBuzz instead of numbers divisible by both 3 and 5.
for(var i = 1; i <= 100; i++) {
switch (i) {
case (i%3 === 0 && i%5 === 0):
console.log('FizzBuzz');
break;
case (i%3 === 0):
console.log('Fizz');
break;
case (i%5 === 0):
console.log('Buzz');
break;
default:
console.log(i);
}
}
The problem is, you are switching on the value of variable i. Then you are comparing that with expressions like i % 3 === 0, so the comparison becomes i === (i % 3 === 0).
Instead, you can switch on true, so any expression evaluating to true will be switched into.
for (var i = 1; i <= 100; i++) {
switch (true) {
case (i % 3 === 0 && i % 5 === 0):
console.log('FizzBuzz');
break;
case (i % 3 === 0):
console.log('Fizz');
break;
case (i % 5 === 0):
console.log('Buzz');
break;
default:
console.log(i);
}
}
A switch enters the branch if the case matches the value you are switching for, therefore:
switch (i) {
case (i%3 === 0 && i%5 === 0):
Will enter the first case if:
i === (i%3 === 0 && i%5 === 0)
E.g. for 15 it will be:
15 === true // -> false
so it wont enter the branch. Therefore instead of switching for i you have to switch for true:
switch(true) {
Did you try not to break the switch, because when it matches it won't print the other stuff it is supposed to? Maybe?
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);
}
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.