2012-12-10 70 views
-3

可能重複:
For each in a array. How to do that in javascript?轉換一下PHP代碼的JavaScript(相當於的foreach)

嘿,我需要一些幫助,找到一個很好的從每個PHP相當於爲JavaScript。我試過使用jQuery.each(),但我不確定我是否做得正確。

這是我一直需要轉換的代碼。我需要修復每個foreach到javascript。

if(calculate){ 
    // got complete, calculate possible solution 
    // use decimals? Does this work in the form? 
foreach(values as valName1 => val1){ 
    foreach(operands as op1){ 
     foreach(values as valName2 => val2){ 
      if(valName2 == valName1) 
       continue; 
      foreach(operands as op2){ 
       foreach(values as valName3 => val3){ 
        if(valName3 == valName1 || 
         valName3 == valName2) 
         continue; 
        foreach(operands as op3){ 
         foreach(values as valName4 => val4){ 
          if(valName4 == valName1 || 
           valName4 == valName2 || 
           valName4 == valName3) 
           continue; 
          foreach(operands as op4){ 
           foreach(values as valName5 => val5){ 
            if(valName5 == valName1 || 
             valName5 == valName2 || 
             valName5 == valName3 || 
             valName5 == valName4) 
             continue; 
            parentheses = -1; 
            if(solve(val5, op4, val4, op3, val3, op2, 
              val2, op1, val1, solution, parentheses)){ 
             count++; 
              // Note that since solve() just returns the first result, we won't 
              // display all possible parentheses ordering when there are multiple 
              // solutions 
             if(find_all){ 
              document.write(Solution(val5, op4, val4, op3, val3, op2, 
                  val2, op1, val1, solution, parentheses, find_all); 
             } 
             else{ 
              document.write(Solution(val5, op4, val4, op3, val3, op2, 
                  val2, op1, val1, solution, parentheses, find_all); 
              break; 
             } 
            } 
            parentheses = -1; 
           } 
           parentheses = -1; 
           if(!find_all && count) break; 
          } 
          if(!find_all && count) break; 
         } 
         if(!find_all && count) break; 
        } 
        if(!find_all && count) break; 
       } 
       if(!find_all && count) break; 
      } 
      if(!find_all && count) break; 
     } 
     if(!find_all && count) break; 
    } 
    if(!find_all && count) break; 
} 

if(!count || find_all){ 
    document.write("Found " . count . " solutions."; 
} 

} 
+10

哇。 *代碼在做什麼? –

+1

嗨,男人,只是你!如果代碼被深度嵌套,代碼就會告訴你重新思考你的方法! – GordonM

+0

不知道代碼的作用,我知道一件事:它可以更簡單更優雅 – Matanya

回答

2

如果您正在尋找處理功能(例如,foreach)數據集的underscore.js是一個不錯的選擇。