-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

3
  • 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. Commented Sep 8, 2015 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... Commented Sep 8, 2015 at 12:16
  • Please search before posting. This has been asked several dozen times before, the ground has been thoroughly covered. Commented Sep 8, 2015 at 12:21

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

obj.p1s3, is also valid
@A.T. yes valid but the value is coming from somewhere else and is a variable so the answer is valid
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.

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.