1

I'm sure this is really simple, I just can't work out how to do it.

I want to dynamically make an array from one variable equal to another:

 var pageID = document.getElementsByClassName('page_example')[0].id;

Let's say this returned an id of page_1

 var page_1 = ['value1','value2','value3'];
 var page_2 = ['value4','value5','value6'];
 var page_3 = ['value7','value8','value9'];

var page_array = (then have the associated pageID's array here)

So in this example,

page_array would equal ['value1','value2','value3']
2
  • I'm not sure to fully understand, but you could do this: var page_array = eval("page_1"). You should provide more code Commented Mar 7, 2016 at 14:03
  • Looking at your markup will really help Commented Mar 7, 2016 at 14:03

2 Answers 2

0

Instead of storing the array in separate variables, store them in an object with the ids as the key:

var pages = {
    page_1: ['value1','value2','value3'],
    page_2: ['value4','value5','value6'],
    page_3: ['value7','value8','value9']
}

You can access the arrays as though the object was an assosiative array:

var pageID = "page_1";
var pageArray = pages[pageID];
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, all I needed to do was var page_array = eval(pageID). Your method is much cleaner though!
@wadclapp Be extremly careful with eval. The user might change the pageID to some malicious code in the browser developer tools.
0

Depending on what you would like to achieve, you can one of two or three methods.

What I consider the easiest method is an if/else statement:

if (condition) {
 page_array = page_1.slice(0);
} else if (other condition) {
 page_array = page_2.slice(0);
} else if...

Another method you can use, again depending on what your ultimate goal is, would be a for loop:

for (var i = 0; i < numOfDesiredLoops; i++) {
  page_array = page_1.slice(0, i);
}

Or you could use a combination of both:

for (var i = 0; i < numOfDesiredLoops; i++) {
  if (condition) {
    page_array = page_1.slice(0); 
  } else if (other condition) {
    page_array = page_2.slice(1);
  } else if...
}

With more information on why you need this variable to change, I can give you a better answer.

edit: keep in mind the arguments of .slice() can be whatever you want.

1 Comment

Your Answer

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