Switch statement goes directly to default even with breaks - javascript

What I'm attempting to do is to create a switch statement that takes data from the JSON API and prints it depending on the location of the user.
For example, if the user is located in the US, then it prints only the city and state. If located outside of the US, it prints the city and the country. If the city is an empty string, then it prints only the country.
As of now, no matter what location I set my VPN to, it goes to the default case(city and country).
var location;
var city;
var state;
var country;
$.getJSON("http://ipinfo.io", function(data) {
console.log(data);
location = data.loc;
city = data.city;
state = data.region;
country = data.country;
switch (data) {
case country === 'US':
$("#yourCity").html(city + ", " + state);
break;
case city === "":
$("#yourCity").html(country);
break;
default:
$("#yourCity").html(city + ", " + country);
}
I chose to use a switch statement rather than an if statement because I may want to add more cases later on down the line.
Any help would be greatly appreciated.

You need to pass something more specific than just data in your switch statement. Since data is an object and not country or city it goes straight to the default.
I think you are thinking that when it goes through the case it looks through the object and sees if it has the value country or city, but it doesn't. You need to pass something like switch(data.location) and then data.location value is either country or city. So you might need to move things around a bit. Hope that makes sense!

Switch-case statement can be used only to compare one value with several others. According to your code sample, you have tried compare both country and city using switch case. That is not possible, definitely you'll have to use if-else statement handle this.
Please consider following method.
var location;
var city;
var state;
var country;
$.getJSON("http://ipinfo.io", function(data) {
console.log(data);
location = data.loc;
city = data.city;
state = data.region;
country = data.country;
if(country === 'US'){
$("#yourCity").html(city + ", " + state);
}else{
if(city===''){
$("#yourCity").html(country);
}else{
$("#yourCity").html(city + ", " + country);
}
}
You also used switch case statement in a wrong way. Switch case statements doesn't have arithmetic compare symbols. Try switch case statement as follows.
var day = new Date().getDay();
switch (day) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}

You're not using the switch case properly.
Basically, you need to pass a specific type of data. Currently, the switch variable is not a country nor a city hence it goes straight to the default.
further reading:
JavaScript Switch Statement

Related

Do loop with a switch case in javascript

//I need to add one to the total each time the error name is input. For example if I type "S" in the prompt, then it will add 1 to the total steering and if I type "W", it will add to wiper. The loop should run until i entered a null or zero value and calculate the total errors.
<html>
<head><title>Charge Calculator</title></head>
<body>
<script type="text/javascript">
//Declaring Variables
var day;
var data="";
var steering = 0;
var turbo =0;
var wiper =0;
day = prompt("Enter day: ","");
var BR="<br/>";
do
{
data = prompt("Enter Data: ","");
data = input.nextLine();
switch(data)
{
case 'S':
steering++;
break;
case 'T':
turbo++;
break;
case 'W':
wiper++;
break;
}
}
while(data == "")
document.write("day: " +day +BR); //Display destination name
document.write("Steering issue: " +steering +BR);
document.write("turbo Issue: " +turbo +BR);
document.write("wiper Issue: " +wiper +BR);
</script>
</body>
</html>
There are many things to be improved in your code. Be aware that the write() expression will potentially destroy parts of your html-based page. Find out about DOM manipulation commands instead.
The following snippet demonstrates in a very short way how you could collect your inputs. I used your prompt() method simply to show that it can be done but I would always prefer a simple input field instead.
const counts={s:0,t:0,w:0};
while (++counts[prompt("Please enter the error type code (s,t or w):").toLowerCase()]) {}
console.log("steering: "+counts.s+
"\nturbo: "+counts.t+
"\nwipers: "+counts.w);
Everything happens within the expression that calculates the result for the while condition: the input value is converted to lower case and then a property of the object counts will be incremented. This will only work (= return a "truthy" result) for already initialised properties like s, t or w. For all other cases an increment cannot be calculated, resulting in an "NaN" ("not a number") result. This will then end the while loop.
Seems like recursion could be more appropriate solution here. Though #Cartsten's one looks absolutely ok also.
function count() {
const counts = {
s: 0,
t: 0,
w: 0
};
const checkCounts = () => {
let input = prompt(
'Please enter the error type code (s,t or w):'
).toLowerCase();
if (counts[input] !== undefined) {
++counts[input];
return checkCounts();
}
};
checkCounts();
console.log(
`steering: ${counts.s} \n turbo: ${counts.t} \n wipers: ${counts.w}`
);
}
count();

Unknown error in google app script formula

Im trying to create a custom formula using Google App Script for a spreadsheet that given two different variables returns one numeric value.
Eg.
a = true and b = "something" return 50
Here is the code;
function VALOR_KM(vehiculo, cliente) {
var especial = (vehiculo == 'especial') ? true : false;
var valor = 0;
function costo(c) { valor = c };
switch (cliente) {
case 'asegurado':
if (especial) costo(80)
else costo(55);
break;
case 'particular':
if (especial) costo(90)
else costo(66);
break;
case 'AA':
costo(3);
break;
case 'audi':
costo(4);
break;
default:
costo(0);
break;
}
return valor;
};
But when i try to use it in a spreadsheet it gives me the #ERROR! "error analyzing formula" code. And I cant tell why its not working, because if i run the script like JavaScript it works.
Despite the formula being correct, it is not being called properly - which is what causes the error analizying formula error message.
As explained here:
The function separator for each Sheet is dependent on the the country chosen from File> Spreadsheet setting "Locale" - For example if you choose United States then function separator is comma but if you choose Germany then it will be a semicolon. What I have notice that each time you change the Country functions separator are automatically changed.
So essentially you just have to use the appropriate argument separator for your locale (which may be either ; or ,).
See if this works
function VALOR_KM(vehiculo, cliente) {
var valor;
switch (cliente) {
case 'asegurado':
valor = (vehiculo === 'especial') ? 80 : 55;
break;
case 'particular':
valor = (vehiculo === 'especial') ? 90 : 66;
break;
case 'AA':
valor = 3;
break;
case 'audi':
valor = 4;
break;
default:
valor = 0;
break;
}
return valor;
};

(Javascript prompt app ) switchcase inside switchcase will not run

I am making an app (idk what to call it) that shows up as a prompt and alert.
However, my code seems to unable to run a switchcase inside a switchcase which I use to add an order into a cart and also use to show the content of the cart.
Another way of saying what my problem is:
I cannot add items to my cart
I cannot access my cart (the prompt just closes itself)
To be more clear I will include my code below along with a codepen link of it and I will comment where I think the problems are.
All input is greatly appreciated.
Thanks!
arrayCart =[];
totalBill = parseInt(0);
cartContent = arrayCart.length;
for(;;)
{
userInput = parseInt(prompt('1. Menu\n2. Your Cart\n3. Payment\n4. Exit'))
switch(userInput)
{
// This is to go to Menu
case 1:
inputPesanan = prompt('Silahkan pilih menu yang diinginkan:\n1. Paket Bento A\n2. Paket Bento B\n3. Paket Bento C')
// I think the 1st problem starts here
switch(inputPesanan)
{
case 1:
arrayCart.push('Paket Bento A - Rp20.000\n');
totalBill += parseInt(20000);
break;
case 2:
arrayCart.push('Paket Bento B - Rp25.000\n');
totalBill += parseInt(25000);
break;
case 3:
arrayCart.push('Paket Bento C - Rp30.000\n');
totalBill += parseInt(30000);
break;
}
break;
// and the 1st problem ends here
// This is to check the Cart's content
case 2:
// And I think the 2nd problem starts here
inputKeranjang = alert('Isi Keranjang Anda\n' + arrayCart + '\n\n' + 'Total Tagihan Anda: \n' + totalBIll)
break;
// and it ends here
//----------- everything under this line seems to be working fine ---------------------------------------
// This is to input how much money you would like to pay with and calculate the change or deficit (if any)
case 3:
inputPayment = parseInt(prompt('Total Tagihan Anda :\nRp' + totalBill + '\n\nBerapa uang yang Anda akan bayarkan?'));
switch(true)
{
case inputPayment<totalBill:
alert('Uang Anda kurang sebesar Rp ' + parseInt(totalBill-inputPayment));
break;
case inputPayment>totalBill:
alert('Anda akan mendapat kembalian sebesar Rp' + parseInt(inputPayment-totalBill));
break;
case inputPayment=totalBill:
alert('Uang Anda pas');
break;
}
break;
}
// This is to end the infinite loop and close the app
if(userInput === 4)
{
break;
}
}
I'm not the javascript developer but as far switch statement goes,
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
So whatever you pass as input to the switch("YouInput") it checks for that in all cases, so If you pass Int as your Input in first switch, let say 1 then case 1: will execute if you pass 100 case 100: if no case match default will and if you pass String let say "Yosia" then if there is any case "Yosia": that will execute
So in your second switch cases you are checking for case 1: , case:2 but I don't think your "inputPesanan" is of type int beacuse in everywhere else you are using some parseIn but not there so may be print and check you "inputPesanan" it will not be 1, 2, or cases you are looking for.

Javascript using a switch statement with `case x` for a wide range of numerical values x

I wish to use case within a switch switch statement like so:
case 'transfer' + amount:
sql.get(`SELECT * FROM scores WHERE userId ="${userID}"`).then(row => {
sql.run(`UPDATE scores SET points = ${row.points - amount} WHERE userId = ${userID}`);
bot.sendMessage({
to:channelID,
message: `You have transferred ` + amount + ` points. You currently have ${row.points} points.`
})
break;
If it sees transfer10 I want the code to take that value 10 to be amount however I have no idea how to do that.
Thanks in advance :)
I do not think you can create switch statement with dynamic-generated case statements. I also do not see any real advantage of doing this, plus the logic behind this it would be hard to understand from anyone else who will be reading the code.
What about using the switch statement do determine the art of action and accessing the _amount_in the case statements ?
var amount, action;
// some code
...
amount = 2;
// some code
...
action = 'transfer' // or delete, update ...
// some code
...
switch(action) {
case 'transfer':
// do some SQL and access the amount
...
break;
case 'delete':
// do some SQL and access the amount
break;
default:
// some default action
}
If you really need something like a dynamically-created switch-statement look at the first answer from this question.

javaScript placeholder in array for pattern match

I have a js array like that:
let data = [{status:"stay",points:[1,2,3,4,5]}, {status:"move",points:[1,2,3,4,5]},{status:"stay",points:[1,2,3,4,5]}]
And I want to do some pattern match, here is my code:
switch (data){
case [{status:"move",_},{status:"stay",_},{status:"move",_}]:
console.log("successfully!")
}
And I don't care the points array, but in js the placeholder "_" not exist, actually I know other method to do this, but if we just use switch-case, can it be solved?
I am a newbie of js, anynoe knows how to do it?
If I understand what you're trying to do correctly, you might try reducing your array to a string, and then use that string in the switch statement. Something like this:
var actionString = ""
data.forEach(function(datum) {
actionString += datum.status + ' ';
});
// Remove extra space at the end
actionString.trim();
console.log(actionString); // "move stay move"
Then your switch statement would be:
switch(actionString) {
case "move stay move":
console.log('success!');
break;
case "stay move stay":
console.log('failure?');
break;
/* etc */
}
Try
switch (data.status){
case "stay":
case "move":
console.log("successfully!")
break;
}
Documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Categories

Resources