2016-11-17 157 views
0

我有一個日期數組。加載時我想用Moment JS解析這些日期,然後在myTable的B列中顯示這些日期。嵌套for循環返回錯誤值

我到目前爲止返回數組的最後一個值3次,我不知道爲什麼。

function loadFunction() { 

    var cellData = ["2016-08-24 12:45", "2016-08-24 16:00","2016-08-24 13:00"]; 

    var myTable = document.getElementById("myTable"); 

    var times = []; 

    for (var i =0; i <cellData.length; i++) { 

     var date = moment(cellData[i]).format('MM/DD/YYYY hh:mm a'); 
     times.push(date); 

    for (var j=1; j < 6 ; j+=2) { 

     myTable.rows[j].cells[1].innerHTML = times[i]; 

     } 
    } 
} 


<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script> 

<body onload="loadFunction()"> 

<table id="myTable"> 
    <thead> 
     <tr> 
      <th colspan="3">Table</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td>A</td> 
      <td>B</td> 
      <td>C</td> 
     </tr> 
     <tr style="display:none;"> 
      <td colspan="3"></td> 
     </tr> 
     <tr> 
      <td>A</td> 
      <td>B</td> 
      <td>C</td> 
     </tr> 
     <tr style="display:none;"> 
      <td colspan="3"></td> 
     </tr> 
     <tr> 
      <td>A</td> 
      <td>B</td> 
      <td>C</td> 
     </tr> 
     <tr style="display:none;"> 
      <td colspan="3"></td> 
     </tr> 
</tbody> 
</body> 

回答

0

您的第二個for對每個值重複3次。所以在單元格的最後一個值中,它將設置到單元格1 3和5中相同的值。嘗試申報並迭代後外變量改變Ĵ

function loadFunction() { 
 

 
    var cellData = ["2016-08-24 12:45", "2016-08-24 16:00","2016-08-24 13:00"]; 
 

 
    var myTable = document.getElementById("myTable"); 
 

 
    var times = []; 
 
    var j=1; 
 
    
 
    for (var i =0; i <cellData.length; i++) { 
 

 
     var date = moment(cellData[i]).format('MM/DD/YYYY hh:mm a'); 
 
     times.push(date); 
 

 
     myTable.rows[j].cells[1].innerHTML = times[i]; 
 
     j += 2; 
 
      
 
    } 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script> 
 

 
<body onload="loadFunction()"> 
 

 
<table id="myTable"> 
 
    <thead> 
 
     <tr> 
 
      <th colspan="3">Table</th> 
 
     </tr> 
 
    </thead> 
 
    <tbody> 
 
     <tr> 
 
      <td>A</td> 
 
      <td>B</td> 
 
      <td>C</td> 
 
     </tr> 
 
     <tr style="display:none;"> 
 
      <td colspan="3"></td> 
 
     </tr> 
 
     <tr> 
 
      <td>A</td> 
 
      <td>B</td> 
 
      <td>C</td> 
 
     </tr> 
 
     <tr style="display:none;"> 
 
      <td colspan="3"></td> 
 
     </tr> 
 
     <tr> 
 
      <td>A</td> 
 
      <td>B</td> 
 
      <td>C</td> 
 
     </tr> 
 
     <tr style="display:none;"> 
 
      <td colspan="3"></td> 
 
     </tr> 
 
</tbody> 
 
</body>

+0

完美的價值,謝謝。 –