Using a string to access a variable

I currently have a Javascript function that uses a string to refer to the name of an object and uses its properties. I am currently using eval () to get the desired effect, which, as I know, is very, very wrong. Here is an example of how I am now achieving what I want:

var stringToObjectRef = function() {

    var myTestVar = "myTestObject";
    var myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };

    var myValue = eval(myTestVar + '.item1');

    alert(myValue);

}();

I tried using something like [myTestVar] .item1, but that returns undefined. What is the correct syntax to achieve this?

Thanks in advance.

+3
source share
3 answers

If you are talking about the part item1you are looking for:

myValue = myTestObject["item1"];

No need for eval. (There almost never happens.)

myTestObject "myTestObject", , , eval. , , , . :

var stringToObjectRef = function() {

    var objects = {};

    var myTestVar = "myTestObject";
    objects.myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };

    var myValue = objects[myTestVar].item1;

    alert(myValue);

}();

, , , , :

var x = (function() { return 5; })();

var x = function() { return 5; }();

, , , - .

+7

:

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

eval ("myTestObject [\" item1 \ "") should do the trick since myTestObject.item1 is short for myTestObject ["item1"]

How to dynamically refer to an object?

0
source

Source: https://habr.com/ru/post/1741254/


All Articles