How to make a variable addressable by name as string in JavaScript?

Goint off of Triptych's stuff (Which Thanks)...

(function(){
  (createSingleton = function(name){  // global
    this[name] = (function(params){
      for(var i in params){
        this[i] = params[i];
        console.log('params[i]: ' + i + ' = ' + params[i]);
      }
      return this;
    })({key: 'val', name: 'param'});
  })('singleton');
  console.log(singleton.key);
})();

Just thought this was a nice little autonomous pattern...hope it helps! Thanks Triptych!


Use a Javascript object literal:

var obj = {
    a: 1,
    b: 2,
    c: 'hello'
};

You can then traverse it like this:

for (var key in obj){
    console.log(key, obj[key]);
}

And access properties on the object like this:

console.log(obj.a, obj.c);

What you could do is something like:

var hash = {};
hash.a = 1;
hash.b = 2;
hash.c = 'hello';
for(key in hash) {
    // key would be 'a' and hash[key] would be 1, and so on.
}

Tags:

Javascript