JavaScript For循环使用If Else语句

时间:2013-02-22 00:43:05

标签: javascript

我正在寻找一种更简单的方法来处理这些多个If Else语句,有几百个。我猜最好只使用If Else中的另一个For循环,但请告诉我你们所有建议,谢谢!

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;
}

3 个答案:

答案 0 :(得分:4)

请试试这个:

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;
}

答案 1 :(得分:0)

未对此进行测试,我认为i<(list.length<18?list.length:18)可能有误。它只是为了停止处理链接,假设你不需要超过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;
  }
}

答案 2 :(得分:-1)

您可以执行切换声明。

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

    case 2:
     tileid = 2;
    break;

    default:
     tileid = 0;
}