0

I have an array

    var n = ["Joe", "Peter", "Mary", "Chris", "Dave", "Sally", "Pat", "John", "Larry", "Andrew"];

And I want to create a variable for each of the strings in the array, i.e.

    var Joe;
    var Peter;
    var Mary;

I have come across this for MatLab, but is there some way of doing this with Javascript?

Here's a Fiddle of how I would think of doing it but obviously it doesn't work!

1
  • 3
    why? this just complicates things. Commented Jul 23, 2014 at 21:25

4 Answers 4

6

...is there some way of doing this with Javascript?

Not in the generic case, no. (Ugh, see below.) You can do it with global variables, like this:

var index;
for (index = 0; index < n.length; ++index) {
    window[n[index]] = /*...whatever value you want the global to have...*/;
}

...but that only works for globals (and window is specific to the browser environment, although it's possible to do something analogous outside browsers), and barring some really specific reason for doing it, it's not a good idea.

You can create an object with properties for each of those names:

var obj = {};
var index;
for (index = 0; index < n.length; ++index) {
    obj[n[index]] = /*...whatever value you want the global to have...*/;
}

...which is basically the global variable case, but with an object and not globals. But again, unless you have a really good reason to do it, there's little point (although it's not as harmful as creating a bunch of globals).


Okay, that's not quite true. You can do it like this:

var index;
for (index = 0; index < n.length; ++index) {
    eval("var " + n[index]);
}

That will actually create variables in the current scope with the names from n. I don't recommend it. :-)

Sign up to request clarification or add additional context in comments.

2 Comments

I wouldn't say it can't be done, but an object is certainly the better alternative.
@cookiemonster: Ugh, you're right. eval Thanks for the nudge.
3

I wouldn't suggest doing that, but it would be possible by using:

var i;
for(i=0; i<n.length; i++) {
    window[n[i]] = ...;
}

I would suggest wrapping them in an object using:

var i, holder = {};
for(i=0; i<n.length; i++) {
    holder [n[i]] = ...;
}

Comments

0

You could use an associative array. So it might look something like this:

var array = {
     "John": 1,
     "Mary": 284
};

Then you would reference the value via array["John"] and would get 1 back.

1 Comment

They're called "objects" in JavaScript.
0

You can create a object like this:

var names = {
    Joe: "...",
    Mary: "...",
    // etc...
}

And access:

names.Joe

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.