1

im practicing javascript and i have arrays (more than 10) which have strings in it var p = ["one","two","three","four"]; var q = [//somthing here]

and another array which is created by a function which select n store some array names for further actions

var m = ["p","q","r","s"];

how can i use element of array m as the varable/array name like:

<button onclick="testArrays(dest, m[0])">desti</button>

must have to work like this

<button onclick="testArrays(dest, p)">desti</button>

all i want to say that how can i use m[0] as a variable

im not using objects

victor
  • 15
  • 4
  • The answer is to use an object with a `name -> array` mapping. If the runtime behavior of your code depends on variable names, then you are likely doing something wrong. – Felix Kling Jul 11 '15 at 14:42
  • @FelixKling , why are you marking this question as a duplicate i m not using objects here and ive already searched the question you are seggesting. please just solve my problem , i m just begginer in javascript – victor Jul 11 '15 at 14:56
  • 1
    The linked question contains all possible solutions to this problem. And the point is at you *should* be using an object instead. If you think you should not, then you should explain your use case in more detail. But again, the linked question pretty much covers all possible solutions. – Felix Kling Jul 11 '15 at 14:59
  • 1
    We know you're not using objects. That's the point. You should be. If you actually heed the advice given, you'll find that objects are the proper solution in JS. –  Jul 11 '15 at 15:00

1 Answers1

0

As a variable where? If it's a property of an object you can use object[m[0]]

And if it's on the global scope you can use the window object window[m[0]]. If it's a variable inside a function you should rethink your approach. There is a way that starts with e and ends with val and you should never, ever use it.

Jan
  • 5,688
  • 3
  • 27
  • 44
  • can you show me please how with eval – victor Jul 11 '15 at 14:43
  • `eval(m[0])` would return your `p` variable, but you should never ever use this in an actual real-world application. It's a horrible practice and if you HAVE to use it, you've taken the wrong approach to your problem. – Jan Jul 11 '15 at 14:46
  • its not working when i m printing it using the function it says [object HTMLHtmlElement] – victor Jul 11 '15 at 14:49
  • and usin window[] its saying undefined – victor Jul 11 '15 at 14:52
  • Then `p` in your scope is a html element and not an array. With the code you posted, it works. http://jsfiddle.net/506x1wuj/ But please learn to code the proper way instead. – Jan Jul 11 '15 at 14:57