Toggle statement, it doesn't work with hint
I just learned switch statements. I have practiced this by creating something. When I set the value of the variable to a number, it works, but when I ask the user for a number, it always outputs the default statement .
It works with this code:
confirm("You want to learn basic counting?");
var i = 0;
switch (i) {
case 0:
console.log(i);
i++
case 1:
console.log(i);
i++;
case 2:
console.log(i);
i++;
case 3:
console.log(i);
i++;
case 4:
console.log(i);
i++;
case 5:
console.log(i);
i++;
case 6:
console.log(i);
i++;
case 7:
console.log(i);
i++;
case 8:
console.log(i);
i++;
case 9:
console.log(i);
i++;
case 10:
console.log(i);
console.log("Congratulations!");
break;
default:
console.log("Buzz, wronghh");
break;
}
But when I ask the user for a value, it doesn't work. The code below doesn't work:
confirm("You want to learn basic counting?");
var i = prompt("Type any number from where you want to start counting[Between 0 and 10]");
switch (i) {
case 0:
console.log(i);
i++
case 1:
console.log(i);
i++;
case 2:
console.log(i);
i++;
case 3:
console.log(i);
i++;
case 4:
console.log(i);
i++;
case 5:
console.log(i);
i++;
case 6:
console.log(i);
i++;
case 7:
console.log(i);
i++;
case 8:
console.log(i);
i++;
case 9:
console.log(i);
i++;
case 10:
console.log(i);
console.log("Congratulations!");
break;
default:
console.log("Buzz, wronghh");
break;
}
+3
source to share
2 answers
The statement switch
performs a strict comparison between the input expression and case expressions. The following will result in:
var i = 1;
switch (i) {
case "1":
console.log('String 1');
break;
case 1:
console.log('Number 1');
break;
}
// Number 1
var j = "1";
switch (j) {
case "1":
console.log('String 1');
break;
case 1:
console.log('Number 1');
break;
}
// String 1
The prompt function returns a string like this:
- Change your case statements to
case "1":
,case "2":
- Listen for user input of a number using
i = Number(i)
+2
source to share