Using a string to access a variable

后端 未结 3 445
难免孤独
难免孤独 2021-01-14 17:23

I currently have a Javascript function that uses a string to reference an object name and acces its properties. I\'m currently using eval() to get the the desired effect whi

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 17:36

    Try this instead:

    var stringToObjectRef = function() {
      var myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };
      var myValue = myTestObject['item1'];
      alert(myValue);
    }();
    

提交回复
热议问题