📜  如何使字符串引用javascript代码示例中的对象

📅  最后修改于: 2022-03-11 15:03:18.532000             🧑  作者: Mango

代码示例1
// 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
}