0

I have the array

var login = ["login", "php"];

And the variable withoutNumberSign which is set based on the URL and should in this case be defined as login. I need to use the array based on the value of withoutNumberSign. How would I do that?

6
  • 1
    What is your question? What are you trying to accomplish specifically? Commented Jan 6, 2016 at 23:18
  • 2
    stackoverflow.com/help/how-to-ask Commented Jan 6, 2016 at 23:20
  • @Gnarlywhale I need to use the array based on the value of withoutNumberSign. How would I do that? Commented Jan 6, 2016 at 23:23
  • Are you referring to selecting an array based on the string variable in withoutNumberSign? Commented Jan 6, 2016 at 23:26
  • Do you have multiple other arrays besides login? Commented Jan 6, 2016 at 23:28

1 Answer 1

2

The one solution I can see is to eval the value of withoutNumberSign and assign that to a new variable, which then you can use to dereference the array you want to use. So that would look like:

var login = ["login", "php"];
// This for testing
// var withoutNumberSign = "login";
var newvar = eval(withoutNumberSign);
console.log(newvar[0]);

A more elegant solution IMO would be to use an associative array at your first layer, on which you'd perform a lookup based on withoutNumberSign.

var associativeArray = {};
associativeArray["login"] = ["login", "php"];
console.log(associativeArray[withoutNumberSign][0]);
Sign up to request clarification or add additional context in comments.

2 Comments

The associativeArray solution is a much cleaner implementation.
I used the associative array and it works perfectly! Thanks!

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.