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
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.
answered Jul 17, 2018 at 18:22
Bucket
7,5599 gold badges38 silver badges48 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Patrick Roberts
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.Bucket
@PatrickRoberts - True. Alternatively, changing
dataSet.push([]) to dataSet[i] = [] would mitigate this issue.Patrick Roberts
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 */lang-js