1

嗨,我正在使用 highcharts,我正在尝试动态创建一个数组数组以提供给图表。

我想出了如何制作数组的数组,但输出格式不是 highcharts 想要提供的。

我正在尝试动态生成一个数组,输出将是:

[[10, 3500], [11, 3400], [12, 3300], [13, 3200], [14, 3100], [15, 3000], [16, 2900], [17, 2800], [ 18, 2700], [19, 2600], [20, 2500]]

但我得到的是:

10,3500,11,3400,12,3300,13,3200,14,3100,15,3000,16,2900,17,2800,18,2700,19,2600,20,2500

如何让 Javascript 输出括号以使格式正确?

<html>
<head>

  Max Price: <input id="max_price_input" type="number" value=3500><br>
  Min Price: <input id="min_price_input" type="number" value=2500><br>
  Max People: <input id="max_people_input" type="number" value=20><br>
  Min People: <input id="min_people_input" type="number" value=10><br>


<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script>

chart = void 0;

$(document).ready(function() {
    var max_price, min_price, max_people, min_people, chart;
    max_price=document.getElementById("max_price_input").value;
    min_price=document.getElementById("min_price_input").value;
    max_people=document.getElementById("max_people_input").value;
    min_people=document.getElementById("min_people_input").value;

    var price_change = max_price - min_price;
    var steps = max_people - min_people;
    var price_step = price_change*1.0/steps;
    var price = max_price;
    var people = 10;
    var priceArray = [];

        for (var i=0;i<=steps;i++)
    { 
        priceArray[i] = [];
                priceArray[i][0] = [people, price];
        price-=price_step;
        people+=1
    }

document.getElementById("price_steps").innerHTML=priceArray

  return chart = new Highcharts.Chart({

    chart: {
      renderTo: "chart",
      type: "spline"
    },
    title: {
      text: "Dynamic Price Chart"
    },
    xAxis: {
      title: {
        text: "People"
      }
    },
    yAxis: {
      plotLines: [
        {
          color: "#FF0000",
          width: 2,
          value: 0
        }
      ],
      title: {
        text: "Price"
      }
    },
    tooltip: {
      formatter: function() {
        return "People: " + this.x + "<br/> Price: " + this.y;
      }
    },
    series: [
      {
        name: "Price",
        data: priceArray
      }
    ]
  });
});

</script>
4

1 回答 1

2

您错误地创建了数组:

// [[[1, 2]]]
var arr = [];
arr[0] = [];
arr[0][0] = [1, 2];

相反,你想要:

for (var i = 0; i <= steps; i++) {
    priceArray[i] = [people, price];
    price -= price_step;
    people += 1
}

您的代码中还有一些其他问题,例如:

您的 html 元素应该进入正文。

这不会显示实际值:

document.getElementById("price_steps").innerHTML=priceArray

相反,请尝试:

JSON.stringify(priceArray);
于 2012-11-04T23:59:30.070 回答