Search code examples
javascriptarrayscanvasjs

Javascript generate code inside


I am beginner, I have this javascript function:

function draw() {
        var chart = new CanvasJS.Chart("chartContainer", {
            title: {
                text: "Title of graph"
            },
            axisX: {
                interval: 0.05
            },
            data: [{
                type: "line",
                dataPoints: [
                    { x: xa[0], y: ya[0] },
                    { x: xa[1], y: ya[1] },
                    { x: xa[2], y: ya[2] },
                    { x: xa[3], y: ya[3] },
                    { x: xa[4], y: ya[4] },
                    { x: xa[5], y: ya[5] },
                ]
            }]
        });
        chart.render();
    }   

It is long time to manually generate axis (x and y), I was tried to take there a while loop. but it not works for me, I think, that I made some mistake.

var i = 0;
while (i < 10)
{

{ x: xa[i], y: ya[i] },

i++;

}

How to make it works inside? To generate axis in code... I was use CanvasJS library to generate charts and I want to make it automatically...

xa and ya are arrays... And on every index is a different value. And with loop I want to show each one.

Thank you for help.


Solution

  • I believe this will work for you. Didn't test it but I feel like it looks ok.

    function draw() {
        var i = 0;
        var pointArray = []; 
    
        while (i < 10)
        {
            pointArray.push({ x: xa[i], y: ya[i] });
            i++;
    
        }
    
        var chart = new CanvasJS.Chart("chartContainer", {
            title: {
                text: "Title of graph"
            },
            axisX: {
                interval: 0.05
            },
            data: [{
                type: "line",
                dataPoints: pointArray
            }]
        });
        chart.render();
    }