0

I have a collection of arrays in my script, as follows

var data0 = [100,10,15,20];
var data1 = [5,100,15,20];
var data2 = [5,10,100,20];
var data3 = [5,10,15,100];

I am getting an input through a click event, which will be the index of the click.

function clickEvent(i) {
var dataNum = "data" + i;
        render2(i); 
    }

I want to set a new var equal to the array at the index which we got as an input. In java, this would have worked. But here, I think dataNum is a string and not an array. Anyway I can set dataNum to array?

For example, when my click event returns index 0, I want dataNum to be set to array data0

Thanks in advance :)

3 Answers 3

1

This would probably be easier if you used one array to hold the data:

var data = [
    [100, 10, 15, 20],
    [5, 100, 15, 20],
    [5, 10, 100, 20],
    [5, 10, 15, 100]
];

then you can access the array index as you would any other array:

function clickEvent(i) {
    var dataNum = data[i];
    render2(i); 
}

Live Demo

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

1 Comment

That makes much more sense than what I was trying to do. #facepalm Thanks! :)
0

You can use eval("data" + i) to evaluate the code in the string and get the array from it.

But I would use the other answer of holding it as an array of arrays.

Comments

0

You should use two-dimensional arrays to deal with it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.