1

我正在用 PHP 做一个网站并有一个图形模块。我已经完成了图形模块,其中 x 轴值和 y 轴值作为数组传递,如下所示:

<script type="text/javascript">
    var chart;
    var chartData = [{
        year: 2005,
        income: 23.5
    }, {
        year: 2006,
        income: 26.2
    }, {
        year: 2007,
        income: 30.1
    }, {
        year: 2008,
        income: 29.5
    }, {
        year: 2009,
        income: 24.6
    }];
</script>

如何在 JavaScript 中使这个数组动态化?

我在这里添加了代码:http: //jsfiddle.net/soumyamohanan/YDmnR/7/但它不起作用,所以我已将图表上传到服务器:http ://rapidsurfing.net/mivotv/graph/bar3D .html

任何帮助都会被接受。

编辑: 更新的小提琴可以在这里找到。

4

2 回答 2

1

根据您的评论,这应该是您想要的:

var year = [2010, 2011, 2012, 2013, 2014],   //assuming you have these 2 arrays
    income = [20, 21, 22, 23, 24],
    chartData = [];

for(var i = 0;i<year.length;i++){
    chartData.push({
        "year": year[i],
        "income": income[i]
    });
}
于 2012-06-30T04:09:28.980 回答
1
var chartData = new Array();
var yearlySalaryObject = {
     year : 2012,
    salary : 100000
};
chartData.push(yearlySalary);

This is the basic idea of what you are trying to do. Since it seems like the underlying concept isn't clear here goes: What you want to do is fill the array with a number of objects. Each object has the 'properties' year and salary. These can be added dynamically to an array using push. All arrays are dynamic in javascript. Arrays in javascript can be used as numerous different data structures. You can also just do.

var chartData = new Array();
chartData.push({ year : 2012, salary : 100000});

*NOTE: I think I severely misunderstood the question...but I am still not certain of that :) if so I don't know how to delete this answer. You should really consider rephrasing and fixing that fiddle though....

Essentially { } denotes an object and [ ] denotes array. That is why you can do what you have above. In fact, you can do as you have above and then push more of the objects into the array. Hopefully that makes sense.

于 2012-06-30T04:14:49.593 回答