0

I wanted to create a function which gets called upon-page load and generates a graph based on what user inputs (multiple datasets, using chart.js).

Decided to rely on prompt() for initial testing, but soon ran into a problem.

function defineDatasets(itt){
    for(i=0; i<itt; i++){
        var dataSet+i=[]; // <--- Does not result in a array called "dataSet0[], ..." etc
    }
}

So my question is, if and how could this be achieved?

1 Answer 1

2

If you're trying to suffix your arrays with an index, why not just make an array of arrays? Also be sure to define your dataSet outside the function scope:

let dataSet = [];

function defineDatasets(itt) {
    for(var i = 0; i < itt; i++) {
        dataSet.push([]);
    }
}

console.log(dataSet[0]); // []

Now instead of referencing these arrays with dataSetN, you can do dataSet[N], where N is the Nth dataSet index.

Sign up to request clarification or add additional context in comments.

3 Comments

It might be beneficial to dataSet = []; before the for loop so that multiple calls to defineDatasets() does not append more empty arrays to dataSet if it's already been initialized.
@PatrickRoberts - True. Alternatively, changing dataSet.push([]) to dataSet[i] = [] would mitigate this issue.
That'd actually be even worse. Consider defineDatasets(20); /* do stuff with dataSet... */ defineDatasets(10); /* expect dataSet.length === 10, but it's actually still 20 */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.