horin
horin

Reputation: 1662

Javascript switch not working

I have the folowing code:

var windowNow = window.localStorage.getItem("windowNow");
switch(windowNow)
{
case 1:
    var link = "http://www.zive.sk/rss/sc-47/default.aspx";
    var listviewID = "feedZive";
    break;
case 2:
    var link = "http://mobilmania.azet.sk/rss/sc-47/default.aspx";
    var listviewID = "feedMobil";
    break;
case 3: 
    var link = "http://www.automoto.sk/rss";
    var listviewID = "feedAuto";
    break;
}

and I know that windowNow === 1 because I have checked it with alert and also to be sure that it realy is 1 I checked it with if(windowNow == 1) { alert ("Window now is 1");} and it worked. But it is not working inside my switch (checked it with alerts).

Upvotes: 2

Views: 9284

Answers (2)

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Do not declare variables inside a switch. Declare them outside the switch and assign inside. Also convert to an integer first.

var windowNow = parseInt(window.localStorage.getItem("windowNow"), 10), link, listviewID;
switch(windowNow)
{
case 1:
    link = "http://www.zive.sk/rss/sc-47/default.aspx";
    listviewID = "feedZive";
    break;
case 2:
    link = "http://mobilmania.azet.sk/rss/sc-47/default.aspx";
    listviewID = "feedMobil";
    break;
case 3: 
    link = "http://www.automoto.sk/rss";
    listviewID = "feedAuto";
    break;
default:
    // default assignment.
}

Upvotes: 2

MaxArt
MaxArt

Reputation: 22617

The items in the localStorage are always strings. Use case "1" and so on.

The problem with your check is that is a loose check, which doesn't check for the data type. You should have tried

if(windowNow === 1) { alert ("Window now is 1");}

Notice the triple =.

Upvotes: 8

Related Questions