gpt4 book ai didi

javascript - 动态数组 JavaScript

转载 作者:行者123 更新时间:2023-11-27 23:03:40 30 4
gpt4 key购买 nike

我对 javascript 有一个简单的疑问。

我有一个由服务器加载的数组:

var dados = [{'ano':2016,'id':1,'mes':1,'valor':87},{'ano':2016,'id':2,'mes':2,'valor':17},{'ano':2016,'id':3,'mes':3,'valor':26}]

获得所需的值后:

var valores = new Array();
for( var i=0; i < dados.length; i++) {
valores.push(dados[i].valor);
}

现在是疑问。如何将值加载到 Chart.js?

var lineChartData = {
datasets : [{
//ommited others configs..
data : valores (I would like load de values of valores here)
}]}

最佳答案

valores var 必须是一个对象而不是常规数组类型。所以它应该是这样的:

enter image description here

看下面的代码:

<html>
<body>
<canvas id='myChart'></canvas>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.js"></script>
<script>
var dados = [
{'ano':2016,'id':1,'mes':1,'valor':87},
{'ano':2016,'id':2,'mes':2,'valor':17},
{'ano':2016,'id':3,'mes':3,'valor':26}
];
var valores = {
// labels like month (mes/mês - I noticed you're a portuguese speaker)
labels: [],
datasets: [
{label: null, data: []}
//more items here whether you want
]
};

for (var index in dados) {
currData = dados[index];
valores.labels.push('Mês ' + currData['mes']);
valores.datasets[0]['data'].push(currData['valor']);
}

var ctx = $("#myChart").get(0).getContext("2d");
var myLineChart = new Chart(ctx).Line(valores);
</script>
</body>
</html>

关于javascript - 动态数组 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36813628/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com