1

我正在尝试为两种(或更多)产品(即驱蚊剂和液体肥皂)生成面积图。我正在使用 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"
            }

        ]
    }]
});
4

1 回答 1

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;
}
于 2015-06-22T22:33:53.967 回答