6

Possible Duplicate:
Javascript dynamic variable name

A very basic question. I want to create a new javascript global variable each time a function is called. The variable should contain the id of the element so that I can easily access it later.

id = 2347

//this function would be called multiple times, hopefully generating a new global each time
function (id)
{
var + id = something
// I want a variable that would be named var2347 that equals something, but the above line doesn't get it.
}

In a later function, I want to access the variable like so:

function two (id)
{
alert(var + id);
}

I'm sure I'm going to have a "doh!" moment when someone is kind enough to answer this.

Community
  • 1
  • 1
Judson
  • 2,265
  • 4
  • 19
  • 20

4 Answers4

7

How about...

var store = (function() {
    var map = {};

    return {
        set: function ( name, value ) {
            map[ name ] = value;
        },
        get: function ( name ) {
            return map[ name ];
        }
    };
})();

Usage:

store.set( 123, 'some value' );

and then...

store.get( 123 ) // 'some value'
store.get( 456 ) // undefined

Live demo: http://jsfiddle.net/jZfft/

Programmers are highly advised to not declare global variables, since the browsers already ship with several hundreds of names in the global namespace. Using the global namespace for your own variables can lead to name-collisions which can then break the program or some of the browser's functionality. Creating new namespaces is free, so don't be shy to do it...

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • +1 for the last paragraph, but I do think this solution is a bit overkill. Instead of a global `map` variable you're creating a global `store` variable. The mere thing this adds is some syntactic sugar in my opinion. – pimvdb Dec 25 '11 at 16:03
  • @pimvdb Yea, it is kind-of an overkill. This is the most basic form of this pattern. It becomes more useful when the get/set behavior is more complex (when multiple commands have to be executed)... – Šime Vidas Dec 25 '11 at 20:43
4

Global variables are properties of the window object, so window.lol and window['lol'] define a global variable lol which can be accessed in any of these ways. The second, window['lol'], can also be used with variable names, like this:

var lol = 123;
var name = 'lol';
var content = window[name]; // window['lol'] == 123

content will now contain 123. Pretty much anything can be put between square brackets [], so you can also do this:

var id = 123;
window['prefix' + id] = 'text';
var content = window['prefix' + id]; // prefix123 == text

Or, in your case:

var id = 2347;
function one(id) {
  window['var' + id] = something;
}
function two(id) {
  alert(window['var' + id]);
}
goto-bus-stop
  • 11,655
  • 2
  • 24
  • 31
  • I believe this is only true for some JS implementations (like those in a browser but not Node.JS for example, there's no `window` there). – Kos Dec 25 '11 at 15:47
  • Oh yes, I forgot about Node and such :(. I think node uses `global` instead of window, don't know about the others... well you could go middle finger to coding standards and eval x]. – goto-bus-stop Dec 25 '11 at 15:52
3

You can save your values to the global hash:

var g = {};

function (id)
{
  g[id] = something;
}

function two (id)
{
  alert(g[id]);
}
bjornd
  • 22,397
  • 4
  • 57
  • 73
3

I would argue that you don't really want to be making lots of global variables. Rather, you can just make one global object or array and attach all your other variables to that. In this case, you probably want an object:

var myIds = {};

function makeSomething(id) {
    // create something that goes with this id
    myIds[id] = something;
}

Then, to fetch that information at some time later, you can retrieve it with this:

var something = myIds[id];

The reason for this suggestion is many-fold. First off, you want to minimize the number of global variables because every global is a chance for a naming collision with some other script you might be using. Second off, when keeping track of a bunch of related data, it's a better programming practice to keep it in one specific data structure rather than just throw it all in the giant global bin with all other data.

It's even possible to create an object that manages all this for you:

function idFactory() {
    this.ids = {};
}
idFactory.prototype = {
    makeSomething: function(id) {
        // create something that goes with this id
        this.ids[id] = something;
    },
    retrieveSomething: function(id) {
        return(this.ids[id]);
    },
    clear: function() {
        this.ids = {};
    } 
};

// then you would use it like this:
var myIds = new idFactory();
myIds.makeSomething(2347);
var value = myIds.retrieveSomething(2347);
jfriend00
  • 683,504
  • 96
  • 985
  • 979