2016-09-15 40 views
0

對於每一天都沒有數據,我想向數組中添加0: 我所做的代碼是錯誤的,因爲它沒有爲缺少的日子添加0。 從1,2,6 ..應該去1,2,3,4,5,6 - 並且導致零到6.結果如下。對於缺失的日子填寫0

 var i = 1; 
     var found = false; 

     try { 
      for (var x = 0; x < @ViewBag.MonthDays; x++) { 
       i = 1; 
       do{ 
        found = false; 
        try { 
         if (i == cheque[x].theDay) { 
          s2.push(cheque[x].theMoney * -1); 
          found = true; 
          console.log("Day: " + cheque[x].theDay + " i " + i); 
          break 
         } 
        } 
        catch (error) { 
         s2.push(0); 
        } 
        console.log(i == cheque[x].theDay, i, cheque[x].theDay); 
        i++ 

       } while ((i < @ViewBag.MonthDays)) 
       console.log(found == false); 
       if (found == false) 
        s2.push(0); 
      } 
     } 
     catch (error){ 
      s2.push(0); 
     } 
     console.log ("Push: " + s2); 

結果:

Day: 1 i 1 
false 
false 1 2 
Day: 2 i 2 
false 
false 1 6 
false 2 6 
false 3 6 
false 4 6 
false 5 6 
Day: 6 i 6 

說天:6 I 6它匹配時。

我知道有更好的方式來做到這一點,有點像這樣的方法:

items = items2.map(row => 
    //is there a matching row in items? 
    items.filter(r => r.theString == row.theString).length == 0 ? 
    //if not, fill with zeros 
      {theString:0, theCount:0} : 
    //if there is, return the items' row 
    items.filter(r => r.theString == row.theString)[0]); 

但只是匹配的是兩個陣列彼此。這個需要每個月的每一天。

+0

什麼是內循環?你也在內循環中遞增,所以這就是爲什麼索引從2跳到6的原因。 – Jasen

+0

@Jasen內部while循環每天都會經過... –

+0

那麼你是在計算每月的每一天的檢查嗎?將輸出延遲到循環之後。將這些推入新陣列並在比較之後打印出來。 – Jasen

回答

-1

這是多麼我已經做到了現在:

  var monthD = new Array(@ViewBag.MonthDays) 
       .join().split(',') 
       .map(function(item, index){ return ++index;}) 
      console.log (monthD); 

      cheque = monthD.map(row => 
       //is there a matching row in items? 
       cheque.filter(r => r.theDay == row).length == 0 ? 
       //if not, fill with zeros 
       {theDay:0, theMoney:0} : 
       //if there is, return the items' row 
       cheque.filter(r => r.theDay == row)[0]); 

      try { 
       for (var x = 0; x < @ViewBag.MonthDays; x++) { 
        s2.push(cheque[x].theMoney * -1); 
       } 
      } 
      catch (error){ 
       s2.push(0); 
      } 

得更好,更快的方法。沒有所有混亂的循環來攪亂我的思想。