我是javascript的新手,我无法弄清楚如何循环一些代码,以便它基本上创建一个数组,然后我可以传递给我的绘图变量。
我不确定从哪里开始。现在我有一大块代码,它接受我的第一个数据集(dataOne)并对其进行格式化,以便它可以进入我的绘图变量。我基本上需要为其他数据集再做三次 - 希望包含example.getDataSets函数以某种方式循环。
有没有好办法呢?
这是我的代码:
的script.js
var example = {};
example.data = {
dataOne: {data: [{"date":1333238400000,"data":23},{"date":1333324800000,"data":37},{"date":1333411200000,"data":49},{"date":1333497600000,"data":54},{"date":1333584000000,"data":30},{"date":1333670400000,"data":19},{"date":1333756800000,"data":15},{"date":1333843200000,"data":19},{"date":1333929600000,"data":145}],
dataTwo: {data: [{"date":1335830400000,"data":63},{"date":1335916800000,"data":77},{"date":1336003200000,"data":66}],
dataThree: {data: [{"date":1341100800000,"data":24},{"date":1341187200000,"data":50},{"date":1341273600000,"data":43},{"date":1341360000000,"data":39},{"date":1341446400000,"data":56},{"date":1341532800000,"data":66}],
dataFour: {data: [{"date":1333238400000,"data":71},{"date":1333324800000,"data":46},{"date":1333411200000,"data":66},{"date":1333497600000,"data":73},{"date":1333584000000,"data":105},{"date":1333670400000,"data":84}]}
}
example.getDataSets = function(){
return ['dataOne', 'dataTwo', 'dataThree', 'dataFour']
}
example.getSeries = function(month){
return example.data[month]
}
example.processData = function(data){
var newData = []
for(var i = 0; i < data.length; i++){
newData.push([data[i].date, data[i].data])
};
return newData;
}
HTML页面中的我的脚本:
$.getScript("script.js")
.done(function() {
var b = example.getSeries('dataOne');
var d = example.processData(b.data);
// first correct the timestamps - they are recorded as the daily
// midnights in UTC+0100, but Flot always displays dates in UTC
// so we have to add one hour to hit the midnights in the plot
for (var i = 0; i < d.length; ++i)
d[i][0] += 60 * 60 * 1000;
var plot = $.plot($("#placeholder"), [d] , options);
非常感谢任何建议!
答案 0 :(得分:0)
尝试
var d = example.processData(b);
作为
console.log('b')
也不会记录您的data
(在b
变量中),但字符串: - )
答案 1 :(得分:0)
您将字符串文字'b'
传递给example.processData
而不是存储在变量b
中的对象。它应该是
var d = example.processData(b);
同样example.getSeries
返回的对象不是数组。该数组位于对象的data
属性中。
此外,您的数据中也存在语法错误,在前3个对象的数组末尾缺少]}
。