Is there a way to do the following without using eval()?
The following function accepts an array of strings where the strings are object names. I iterate over them to ensure that none of them are undefined. I'd like to be able to do this without using eval()
function hasMissingDependencies(dependencies) {
var missingDependencies = [];
for (var i = 0; i < dependencies.length; i++) {
if (eval('typeof ' + dependencies[i]) === 'undefined') {
missingDependencies.push(dependencies[i]);
}
}
if (missingDependencies.length > 0) {
return true;
}
return false;
}
With this, I'm able to pass something like the following and get what I want:
alert(hasMissingDependencies(['App.FooObject', 'App.BarObject']));
I'd prefer to not use eval() but haven't found another way to check if an object is undefined when the object names are passed as strings.
2 Answers 2
Assuming that these are global variables (IE not defined within an inner function scope), you could split on periods and use bracket notation.
something like
function isDefined(name, obj){
if(!obj){
obj = window;
}
var pathArr = name.split(".");
obj = obj[pathArr.splice(0,1)];
if(typeof obj !== undefined){
return pathArr.length ? isDefined(pathArr.join("."),obj): true;
}
return false;
}
Note that unless you're trying to write a requireJS replacement, this is pretty much always a bad idea though. Check if the values exist in the context you're calling the function, and then pass in the values if they exist or null/undefined/some default value otherwise. If you don't control the passing context, ask for objects and then check to see if they're defined.
1 Comment
You seem to want to check if global variables whose names are in your array are defined.
You can build a simple function to get those variable :
function getVar(name) {
var v = window, path=name.split('.');
while (path.length>0 && v) v = v[path.shift()];
return v;
}
which would allow you to test
if (typeof getVar(dependencies[i]) === 'undefined')
hasMissingDependencies(App.FooObject, App.BarObject)throws an error before ever making it into the function if either of those objects are not defined. Am I missing something?Appisundefinedornull, then yes, it would throw an error because you're trying to dereference a null reference. But ifAppis notundefinedornull, then you can pass those two arguments and then just check if they areundefinedin the function, which would be checking if theFooObjectandBarObjectproperties exist on theAppobject.