我正在尝试为两种(或更多种)产品生成区域图,即驱蚊剂和液体肥皂。我正在使用JavaScript库CanvasJS来做到这一点。问题是我在这里需要大约2000个数据点而不是4个硬编码,问题是我无法为两个(或更多)产品生成for循环。任何人都可以帮助我如何创建这个循环吗?
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "area",
name: "Mosquito Repellents",
showInLegend: "true",
dataPoints: [{
y: 83450,
label: "spring"
}, {
y: 51240,
label: "summer"
}, {
y: 64120,
label: "fall"
}, {
y: 71450,
label: "winter"
}
]
}, {
type: "area",
name: "Liquid Soap",
showInLegend: "true",
dataPoints: [{
y: 20140,
label: "spring"
}, {
y: 30170,
label: "summer"
}, {
y: 24410,
label: "autumn"
}, {
y: 38120,
label: "fall"
}
]
}]
});
答案 0 :(得分:3)
您可以使用Math.random函数和函数来完成它。 该函数采用两个参数来设置随机y值的下限和上限。
var mosquitoRepellentsDataPoints = generateDataPoints(10000, 40000),
liquidSoapDataPoints = generateDataPoints(10000, 40000);
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "area",
name: "Mosquito Repellents",
showInLegend: "true",
dataPoints: mosquitoRepellentsDataPoints
}, {
type: "area",
name: "Liquid Soap",
showInLegend: "true",
dataPoints: liquidSoapDataPoints
}]
});
function generateDataPoints(lowerLimit, upperLimit) {
var i,
arr = [],
seasons = ['spring', 'summer', 'fall', 'winter'];
for (i = 0; i < 2000; i++) {
arr.push({
y: lowerLimit + Math.round(Math.random() * (upperLimit - lowerLimit)),
label: seasons[Math.floor(Math.random() * seasons.length)]
});
}
return arr;
}