a[2] is a random integer variable from 1 - 100. When it is less than than 33 it changes to red but when it is above 33 it stays black. Anyone got an idea why it ignores the last 2 cases?
<script type="text/javascript">
switch (a[2]) {
case < 33:
document.getElementByID('speechstat').style.color = "red";
break;
case >= 33 && <= 66:
document.getElementByID('speechstat').style.color = "blue";
break;
case > 66:
document.getElementByID('speechstat').style.color = "green";
break;
}
</script>
In JavaScript, switch statements look differently than what you've posted. For example, here's some documentation on switch statements on MDN.
If you want to check for ranges, you should check with regular if/else statements.
<script type="text/javascript">
var color;
// Check the possible value ranges.
if (a[2] < 33) { color = 'red'; }
else if (a[2] >= 33 && a[2] <= 66) { color = 'blue'; }
else if (a[2] > 66) { color = 'green'; }
document.getElementByID('speechstat').style.color = color;
</script>
In Javascript, you can't compare a variable with switch but you can do so indirectly as this post's answer shows: switch statement to compare values greater or less than a number
With a few edits and adding some html to check if everything works this is how you would do this in your case:
<!DOCTYPE html>
<html>
<body>
<p id="speechstat1"></p>
<p id="speechstat2"></p>
<p id="speechstat3"></p>
<script type="text/javascript">
var a = 34; //You can set this to whatever you want or a user's input
switch (true) {
case (a<33):
document.getElementById("speechstat1").innerHTML = "red works";
break;
case a>= 33 && a<= 66:
document.getElementById('speechstat2').innerHTML = "blue works";
break;
case a> 66:
document.getElementById("speechstat3").innerHTML = "green works";
break;
}
</script>
</body>
</html>
I put in .innerHTML just to show it works, in your case you can replace those
lines with whatever you want to make happen.
I changed Switch to switch
I changed .getElementByID to .getElementById Spelling matters!
If you are testing a variable for two conditions: case >= 33 <= 66: you
need to add the "and" operator case >= 33 **&&** <= 66:
I changed a[2] to a so it doesn't error out because it's not named
correctly
Overall it's easier to use if and else statements for something like this as Morgan Wilde mentioned.
Related
The question is something like this.
You are given a cubic dice with 6 faces. All the individual faces have a number printed on them. The numbers are in the range of 1 to 6, like any ordinary dice. You will be provided with a face of this cube, your task is to guess the number on the opposite face of the cube.
Ex:
Input:
N = 6
Output:
1
Explanation:
For dice facing number 6 opposite face
will have the number 1.
I did it using a normal switch-case by checking all six faces and returning the respective die face number value, which passed my test cases. However, I need to simplify the code. Is it possible for me to do so?
oppositeFaceOfDice(N) {
//code here
switch(N){
case 1:return 6;
break;
case 6:return 1;
break;
case 2:return 5;
break;
case 5:return 2;
break;
case 3:return 4;
break;
case 4:return 3;
break;
default: return -1;
}
}
oppositeFaceOfDice(N) {
switch(N){
case 1||6 : return 6?1:6;
break;
case 2||5: return 2?5:2;
break;
case 3||4: return 4?3:4;
break;
}
}
Use an object literal instead of a switch statement:
function oppositeFaceOfDice(N) {
return {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}[N];
}
Or use #DavidThomas' suggestion above which is particularly clever:
function oppositeFaceOfDice(N) {
if(N < 1 || N > 6) return undefined;
return 7 - N;
}
Other than rewriting the codes, since in your case, the codes are very clear and easy to debug, you can remove the break statement since it's not necessary.
oppositeFaceOfDice(N) {
//code here
switch(N){
case 1:return 6;
case 6:return 1;
case 2:return 5;
case 5:return 2;
case 3:return 4;
case 4:return 3;
}
}
I am trying to run with this code block but it does not work
Switch (num1>num2) {
case 0:
document.write(num2);
break;
case 1:
document.write(num1);
break;
}
You could use something simple as Math.max(5, 10);
const numOne = 5;
const numTwo = 10;
console.log(`Bigger number is: ${Math.max(numOne, numTwo)}`);
Or if you absolutely 'have to' use switch statement, you can try something like this:
const numOne = 5;
const numTwo = 10;
switch(true) {
case (numOne > numTwo):
console.log(`Bigger number is ${numOne}`);
break;
case (numOne < numTwo):
console.log(`Bigger number is ${numTwo}`);
break;
case (numOne === numTwo):
console.log(`${numOne} is equal to ${numTwo}`);
break;
default: console.log(false, '-> Something went wrong');
}
Logical operations return boolean on Javascript.
document.write writes HTML expressions or JavaScript code to a document, console.log prints the result on the browser console.
switch (num1>num2) {
case true:
console.log(num1);
break;
case false:
console.log(num2);
break;
}
switch (with a lower case s) uses strict comparison === so the value of a boolean like 11 > 10 will never === 0 or 1.
You need to test for the boolean if you want to do it this way:
let num1 = 10
let num2 = 20
switch (num1>num2) {
case false:
console.log(num2);
break;
case true:
console.log(num1);
break;
}
If for some reason you were given numbers you could explicitly cast them to booleans with something like case !!0: but that starts to get a little hard on the eyes.
If your goal is to find the max of two numbers, Math.max(num1, num2) is hard to beat for readability.
You would just use the greater than / less than inside of the switch statement.
var x = 10;
var y = 20;
switch(true) {
case (x > y):
console.log(x);
break;
case ( y > x):
console.log(y);
break;
}
In my website user can enter two input . Input1 and Input2 .
So i have to calculate difference with these two number .
difference =input1-input2
so if the difference is greater than 700 i have to apply color red Please see the follow.
dIFFERENCE > 700 = red
dIFFERENCE > 800 = blue
dIFFERENCE > 900 = green
dIFFERENCE > 1000 = white
dIFFERENCE > 1100 = yellow
dIFFERENCE > 1200 = orange
dIFFERENCE > 1300 = purple
etc.. UP TO dIFFERENCE > 5000 = other color
So here i am writing the following jquery ,
var difference= $(".input1")-$(".input2");
if(difference>700){
$(".result").css("color","red");
}
if(difference>800){
$(".result").css("color","blue");
}
etc
is there any easy way to reduce this query ? Like i can store the color in an array and based on the difference i can fetch the result etc .
Please help
EDIT
What i tried is
var difference= $(".input1")-$(".input2");
if(difference >700 && difference<=800){
difference=700;
}else if(difference>=800 && difference<=900 ){
difference=800;
}else if(difference>=900 && difference<=1000 ){
difference=900;
}else if(difference>=1000 && difference<=1100 ){
difference=1000;
}
...
else if(difference>=4900 && difference<=5000 ){
difference=4900;
}
var differnce_array =[];
difference_array[700]="red";
difference_array[800]="blue";
difference_array[900]="green";
difference_array[1000]="white";
etc...
Still it is too much query . So please help to optimize this code
In this case i would create a dictionary, where the keys represent the thresholds and round the difference down to hundreds and look that key up in the dictionary:
var diff = 789; // your value
var diffs = {700: 'red', 800: 'blue', 900: 'green'}; //etc
var diffcol = Math.floor(diff/100)*100; //Floor down to hundreds
if(diffcol in diffs) console.log(diffs[diffcol]); //Validation
1ST APPROACH
You use a hashtable, it's a little bit like a hashset in c# or java, you just pair the keys to the values:
var hash = {
700:"red",
800:"blue",
900:"green",
//etc...
};
And this is how you can get your color:
var difference= $(".input1")-$(".input2");
roundedDifference = Math.floor(difference/100)*100
var color = hash[roundedDifference];
//This will be your color
2ND APPROACH:
You can round the number so you only get the hundereds i.e. 100,200,300,400,etc.
then you can use a switch statement:
var difference= $(".input1")-$(".input2");
roundedDifference = Math.floor(difference/100)*100
switch(roundedDifference) {
case 700:
$(".result").css("color","red");
break;
case 800:
$(".result").css("color","blue");
break;
case 900:
$(".result").css("color","green");
break;
case 1000:
$(".result").css("color","white");
break;
case 1100:
$(".result").css("color","yellow");
break;
case 1200:
$(".result").css("color","orange");
break;
case 1300:
$(".result").css("color","purple");
break;
case ... until 5000
break;
default:
console.log("difference not within range of 700-5000"
}
You can do this up to 5000.
Here is a working code for you:
function submit() {
var difference = $(".input1").val() - $(".input2").val();
console.log(difference)
function getColor() {
var color;
switch (difference) {
case 700:
color = "red";
break;
case 800:
color = "blue";
break;
case 900:
color = "green";
break;
case 1000:
color = "white";
break;
case 1100:
color = "yellow";
break;
case 1200:
color = "orange";
break;
case 1300:
color = "purple";
break;
default:
color = "magenta"
}
return color
}
$(".result").css("color", getColor(difference));
$(".result").html("The color is: "+ getColor(difference));
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" class="input1" placeholder="input1">
<input type="text" class="input2" placeholder="input2">
<button onclick="submit()">Difference</button>
<div class="result"> This changes color</div>
</body>
</html>
Please run the above snippet
Here is a working DEMO
I'm struggling with a simple SVG Image, where I try to update the color of two rectangles.
In Chrome they get updated, In IE(10) the reactangles are just black!
In my controller I'm setting the color via $scope.cvrColor=[random generated color code]
I've made this simple sample to illustrate my problem:
http://jsfiddle.net/mvg123/td7py264/
My Controller:
function testController($scope, $timeout) {
var test = updateSvg();
function updateSvg() {
$scope.startColor = getRandomColor();
$scope.cvrColor = getRandomColor();
$timeout(updateSvg, 1000);
};
function getRandomColor() {
var number = Math.floor(Math.random() * 11);
var color = "";
switch (true) {
case (number < 3):
color = "#808000";
break;
case (number > 3 && number < 8):
color = "#666666";
break;
case (number > 8 && number < 12):
color = "#ff0000";
break;
default: color = "#ffff00";
}
return color;
}
}
Any hints out there?
/Best regards
While your example should work, I have discovered that having expressions inside class or style is somewhat unreliable. It's better to use ng-class and ng-style. So in your case you can write:
<rect ng-style="{fill:startColor, fillOpacity:1}" ... />
http://jsfiddle.net/c5ozbv52/
You must use the angularjs directive "ng-style" :
ng-style="{fill:startColor,fillOpacity:1}"
https://docs.angularjs.org/api/ng/directive/ngStyle
I have a long set of divs where I'd like to change all of their background colors to a random color when someone clicks the "home" button with a cascading delay (which I'll add later). I've been testing this in jfiddle and I can't seem to get it to work.
For example, with a while loop of 1-10 on jsfiddle:
http://jsfiddle.net/PWvaw/17/
Am I having a var scope issue or is there an issue with placing a string/variable combo in a getElementByID method? It seems to show, when I place head tags in the HTML section of jfiddle, the code turns red right after the "getElementById("
switch (randomNumberOne) {
case 1:
document.getElementById(
Any help would be appreciated. I did a search here already and found nothing conclusive, however, I apologize if I missed an answer. Thanks!
Just remove the semicolon in your color codes.
function backgroundColorChange() {
var num = 1;
while (num <= 10) {
var randomNumberMe = Math.floor((Math.random()*10)+1);
console.log(randomNumberMe);
switch (randomNumberMe) {
case 1:
document.getElementById('r' + num).style.backgroundColor = '#db0058';
break;
case 2:
document.getElementById('r' + num).style.backgroundColor = '#80e800';
break;
case 3:
document.getElementById('r' + num).style.backgroundColor = '#ffb700';
break;
case 4:
document.getElementById('r' + num).style.backgroundColor = '#4b5ed7';
break;
default:
document.getElementById('r' + num).style.backgroundColor = '#ffffff';
break;
}
num += 1;
}
}
jsfiddle