I’m trying to use a string as a reference to a variable to pass into a function. For example:
var names = ['Peter', 'John'],
var hasName = function(name){
var params = ['names'];
return $.inArray(name, eval( params[0] )) === -1;
};
How to avoid eval()?
EDIT:
The string from params[0] is comming from a data-qval of an input in my html. The array that contains the actual data can be declared anywhere, params[0] is just a reference to that array passed in as string in data-qval, it’s a parameter. I pasted my plugin’s code here .
http://pastebin.mozilla.org/1598528 Line 101.
Full example: http://jsfiddle.net/elclanrs/ZsS2D/29/
It currently works, I’m just looking for a way get rid of eval()…
In that particular case, just usenames:(See also the note below.) (Your edit makes the above not applicable.)
If you’re trying to look up the
namesarray in some container using the string"names", you’d have to have a reference to the container, e.g.:If there is no container other than the variable scope in which you’re doing this, you’ll have to use
eval. But you can (and usually should) adjust things so you have a container (as above) so you can avoid it. Note that ifnamesis declared at global scope, you do have a container (window).So to summarize:
If
namesis avarat global scope (or an implicit global),window[params[0]]will give you a reference to it.If
namesis already in some container object, you can usecontainer[params[0]]to get a reference to it.If
namesis avarwithin a function, you cannot get at it using a runtime string withouteval; ideally, rather thanvar names = [...];, usevar container = {names: [...]};and then you can usecontainer[params[0]].Note that your function is called
hasName, but it returnstruewhen the array doesn’t have the name andfalsewhen it does. You probably want!== -1, not=== -1.