减少JavaScript if语句

时间:2015-07-18 18:48:25

标签: javascript html if-statement

我需要帮助,我在javascript中有这个功能:

function getPosition(elementToFind, array) {
  var i;
  for (i = 0; i < array.length; i += 1) {
    if (array == elementToFind) {
      return i;
    }
  }
}

如果我愿意减少,那么我有一个周期:

if (
  getPosition(1, arraySomething) == 0 &&
  getPosition(2, arraySomething) == 1 &&
  getPosition(3, arraySomething) == 2 &&
  getPosition(4, arraySomething) == 3 &&
  getPosition(5, arraySomething) == 4 &&
  getPosition(6, arraySomething) == 5 &&
  getPosition(7, arraySomething) == 6 &&
  getPosition(8, arraySomething) == 7 &&
  getPosition(9, arraySomething) == 8 &&
  getPosition(10, arraySomething) == 9 &&
  getPosition(11, arraySomething) == 10
) {
  ...code
}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这样的事情

var isTrue = true;
for(var n = 1; n <=  length; n ++){
    if (getPosition(n, arraySomething) !== (n - 1)){
        isTrue = false;
        break;
    }
}

if (isTrue){
    ...
}else{
    ...
}