Jordan
Jordan

Reputation: 1457

JavaScript For loop in If Else statement

I'm looking for an easier way to process through these multiple If Else statements, there are several hundred. I'm guessing it would be best to just use another For loop inside of the If Else, but let me know you all suggest, thanks!

var hrefs = [];
var list = document.getElementsByTagName("a");
for (var i=0; i<list.length; i++) {
    var hey = list[i].href;
    hrefs.push(hey);
}

if(window.location == 'http://') {
    tileid = <?php echo $numposts.''; ?>;
} else if (window.location == hrefs[7]) {
    tileid = 0;
} else if (window.location == hrefs[8]) {
    tileid = 1;
} else if (window.location == hrefs[9]) {
    tileid = 2;
} else if (window.location == hrefs[10]) {
    tileid = 3;
} else if (window.location == hrefs[11]) {
    tileid = 4;
} else if (window.location == hrefs[12]) {
    tileid = 5;
} else if (window.location == hrefs[13]) {
    tileid = 6;
} else if (window.location == hrefs[14]) {
    tileid = 7;
} else if (window.location == hrefs[15]) {
    tileid = 8;
} else if (window.location == hrefs[16]) {
    tileid = 9;
} else if (window.location == hrefs[17]) {
    tileid = 10;
} else if (window.location == hrefs[18]) {
    tileid = 11;
} else {
    tileid = window.history.state.projid;
}

Upvotes: 2

Views: 239

Answers (3)

David G
David G

Reputation: 96800

Please try this:

var flag = false;

if (window.location == 'http://') {
    tileid = <?php echo $numposts.''; ?>;
} else {
    for (var i = 7; i <= 18; ++i) {
        if (window.location == hrefs[i]) {
             tileid = i - 7;
             flag = true; break;
        }
    }
    if (!flag) tileid = window.history.state.projid;
}

Upvotes: 4

NickSlash
NickSlash

Reputation: 5077

Not tested this, and i think i<(list.length<18?list.length:18) might be wrong. Its just to stop processing links, assuming you dont need anymore than 18.

var hrefs = {};
var list = document.getElementsByTagName("a");
for (var i=0; i<(list.length<18?list.length:18); i++) {
    hrefs[list[i]] = i;
}

if (window.location == 'http://'( {
  tileid = <?php echo $numposts.''; ?>;
} else {
  if (!hrefs[window.location]) {
    tileid = window.history.state.projid;
  } else {
    tileid = hrefs[window.location] - 7;
  }
}

Upvotes: 0

Just Aguy
Just Aguy

Reputation: 327

You can do a switch statement.

switch(urlval){
    case 1:
     tileid = 1;
    break;

    case 2:
     tileid = 2;
    break;

    default:
     tileid = 0;
}

Upvotes: -1

Related Questions