I have seen on some other answers, regarding different questions, to try and avoid using eval() in javascript.
Would using eval() to call an object method cause an issue? It seems to work fine!
Basically, I have along the lines of the following:
var object1 = {
left: "this is left",
right: "this is right"
}
I have a list of objects in a dropdown and depending on which is selected I want to call the "left" or "right" property of that object.
So I get the object name by using:
var objName = document.getElementById("objects").options[document.getElementById("objects").selectedIndex].text.toLowerCase();
//returning, say "object1" from the list
Then I want to use this variable to call up the property of that object. The problem I faced is the variable is a string and was returning undefined for the property ("objName.left is not a function"). However, I found using eval() returned the property correctly, basically:
objName.left; //returns undefined
eval(objName).left; //returns "this is left"
Like I say, this works fine but I have come across a few answer saying to avoid eval(). So is there an alternative way to do this or will this be fine?
I'm still new to this (as you can probably tell) so thanks in advance for any answers, advice and help with this query!