Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new unique global variable each time a function is run in javascript [duplicate]

Tags:

javascript

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.

like image 767
Judson Avatar asked Dec 25 '11 15:12

Judson


3 Answers

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...

like image 95
Šime Vidas Avatar answered Oct 16 '22 20:10

Šime Vidas


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]);
}
like image 26
goto-bus-stop Avatar answered Oct 16 '22 18:10

goto-bus-stop


You can save your values to the global hash:

var g = {};

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

function two (id)
{
  alert(g[id]);
}
like image 3
bjornd Avatar answered Oct 16 '22 20:10

bjornd