1

I have two arrays in js

var array1=new Array("KS","NB","SD","ND","MN");
var array2=new Array("TX","LA","OK","AR");

Some how I will get the name of the array that should be retrieved. Now what I want is, if I get

var arrayTobeSelected = 'array1';

If I console.log arrayTobeSelected, what I get is the string 'array1'. How can I get the elements in the array array1 ?

1
  • just console.log(arrar1); Commented May 26, 2014 at 11:57

3 Answers 3

3

If arrays are in the global scope, you can do:

console.log(window[arrayToBeSelected]);// you can do [0] or [1] to get specific elements
Sign up to request clarification or add additional context in comments.

Comments

1

You're getting a string because:

var arrayTobeSelected = 'array1';

and not:

var arrayTobeSelected = array1;

if you have to get it as string, then just do this:

console.log(eval(arrayTobeSelected));

Comments

0

You can use this code for print all the element of array.

 for(var i = 0; i < array.length; i++){
             console.log(i + " = " + array[i]);
   }
       console.log(array);
       console.log("end");

Comments

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.