Answers for "how to make string refer to object in javascript"

0

how to make string refer to object in javascript

// if variable is in global scope use: window || this
var a = "hello world";
var varName = "a";
console.log( window[varName] ); // outputs hello world
console.log( this[varName] ); // also works (this === window) in this case

// if variable is in local scope use: eval
function () {
  var a = "hello world";
  var varName = "a";
  console.log( this[varName] ); // won't work
  console.log( eval(varName) ); // Does work
}
Posted by: Guest on January-19-2021

Code answers related to "how to make string refer to object in javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language