2017-03-06 252 views
-1

myArray的:For循環打印鍵兩次

[1488559492944,29, 1488556363891,29, 1488554612089,29, 1488553812873,29, 1488555337118,29, 1488556552117,29, 1488555250090,29, 1488553465926,1] 

for (var i = 0; i < keyValueArray.length - 1; i = i + 2) { 
    var xValue = keyValueArray[i].toString(); 
    console.log("x " + xValue); 
    var yValue = parseInt(keyValueArray[i+1]); 
    console.log("y " + yValue); 
    data.addRows([ 
    [xValue, yValue] 
    ]); 
} 

爲什麼這個循環打印這樣的結果:

x 1488559492944 
y 29 
x 29, 1488554612089 
y 29 
x 29, 1488555337118 
y 29 
x 29, 1488555250090 
y 29 ? 

我想要的只是偶數添加到表的價值和不均勻的人作爲什麼鑰匙,但它增加至29秒X的..

+0

使用模運算符找到偶數。 –

+1

無法重現。發佈[mcve]。 –

+3

大概是因爲'data.addRows'內有一個'console.log'。您提供的代碼沒有您提供的輸出。 – Hamms

回答

0

或許這對你

for (var i = 0; i < (keyValueArray.length/2); i++) { 
    var xValue = keyValueArray[2*i].toString(); 
    console.log("x " + xValue); 
    var yValue = parseInt(keyValueArray[2*i+1]); 
    console.log("y " + yValue); 
    data.addRows([ 
    [xValue, yValue] 
    ]); 
} 
解決方案
+0

爲什麼你認爲這應該比他有更好的工作?他的代碼有什麼問題,而不是你的代碼? –

0

假設谷歌的dataTable API,這就是你在看什麼 - 這完全看起來你試圖做的。

google.charts.load('current', {packages: ['corechart']}); 
 
    google.charts.setOnLoadCallback(drawChart); 
 

 
    function drawChart() { 
 
     // Define the chart to be drawn. 
 
     var data = new google.visualization.DataTable(); 
 
     data.addColumn('string', 'Element'); 
 
     data.addColumn('number', 'Percentage'); 
 
     
 
     var keyValueArray = [1488559492944,29, 1488556363891,29, 1488554612089,29, 1488553812873,29, 1488555337118,29, 1488556552117,29, 1488555250090,29, 1488553465926,1] 
 

 
for (var i = 0; i < keyValueArray.length - 1; i = i + 2) { 
 
    var xValue = keyValueArray[i].toString(); 
 
    var yValue = parseInt(keyValueArray[i+1]); 
 
    console.log("x="+xValue+", y=" + yValue); 
 
    data.addRows([ 
 
    [xValue, yValue] 
 
    ]); 
 
} 
 

 

 

 
     // Instantiate and draw the chart. 
 
     var chart = new google.visualization.PieChart(document.getElementById('myPieChart')); 
 
     chart.draw(data, null); 
 
    }
<script src="https://www.gstatic.com/charts/loader.js"></script> 
 
    <!-- Identify where the chart should be drawn. --> 
 
    <div id="myPieChart"/>