用于循环打印键两次

时间:2017-03-06 19:18:54

标签: javascript arrays for-loop

myArray:

[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  ?

我想要的只是将偶数作为值添加到表格中,将不均匀的数字作为键添加,但它会将x添加29秒...

2 个答案:

答案 0 :(得分: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]
  ]);
}

答案 1 :(得分:0)

假设使用google dataTable API,这就是您正在查看的内容 - 这正是您正在尝试做的事情。

&#13;
&#13;
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);
    }
&#13;
<script src="https://www.gstatic.com/charts/loader.js"></script>
  <!-- Identify where the chart should be drawn. -->
  <div id="myPieChart"/>
&#13;
&#13;
&#13;