-1

I'm having a total of 5 arrays. Name of the array will be selected by the user, based on the users selection we need to perform actions.

var p1s1 = ['5', '1', '6'];
var p1s2 = ['2', '4', '7'];
var p1s3 = ['9', '5', '2'];
var p1s4 = ['2', '5', '8'];
var p1s5 = ['7', '4', '2'];

when user selects a dropdown it will have value p1s3. So i need to pick this particular array and perform operations over this. Could anyone please suggest in this regard.

Thanks

Harsha
  • 33
  • 9
  • 6
    You can put them inside an object, and refer to them by key. Getting variables dynamically by name is a recipe for disaster, and not possible in JS anyway. – elclanrs Sep 08 '15 at 12:15
  • 1
    You need to have object which is a collection of `key=>value` pair. In your case key will the the name user selects and value will be the array. I hope this helps... – Rayon Sep 08 '15 at 12:16
  • Please search before posting. This has been asked several dozen times before, the ground has been thoroughly covered. – T.J. Crowder Sep 08 '15 at 12:21

2 Answers2

5

Use object instead:

var obj = {
  p1s1: ['5', '1', '6'],
  p1s2: ['2', '4', '7'],
  p1s3: ['9', '5', '2'],
  p1s4: ['2', '5', '8'],
  p1s5: ['7', '4', '2']
}

Then access array this way:

obj[selected_value_from_dropdown]
ischenkodv
  • 4,205
  • 2
  • 26
  • 34
1

The best way to tackle the solution is having an object rather than multiple variables call it pickUpArray

var pickUpArray = {
  p1s1 : ['5', '1', '6'],
  p1s2 : ['2', '4', '7'],
  p1s3 : ['9', '5', '2'],
  p1s4 : ['2', '5', '8'],
  p1s5 : ['7', '4', '2']
};

Then in your logic say you have the value as val where val = as string 'p1s5' or 'p1s2' etc, which is being passed from the select dropdown. you can select pickUpArray[val]

If you dont have a choice to change this varables you can call eval(val) where val is as string 'p1s5' or 'p1s2' etc, which is being passed from the select dropdown but highly unadvisable.

joyBlanks
  • 6,419
  • 1
  • 22
  • 47