How to construct a string which will pass if(variable)
I'm a jquery novice. I've boiled my code down to the simplest way to describe my problem. But I am having trouble wording it.
if(var1 && var2){
// this works
}
searchMe = var1+" && "+var2;
if(searchMe){
// this doesn't work
}
searchMe = "var1"+" && "+"var2";
if(searchMe){
// still doesn't work
}
I would like to be able to construct that "searchMe
" variable based on user input. Can 开发者_Python百科someone tell me a better way to do this? Thanks!
Not sure but you can make use of eval
function
if(eval(searchMe)){
// this doesn't work
}
A possible way to do this without the dreaded eval
(which really, you should never use) is to just evaluate as you go, and then end up with one variable at the end which is boolean.
var a = true;
var b = a && (false || true) && (1 < 2);
if (b)
document.write('yes');
else
document.write('no');
var c = b && false;
document.write(', ');
if (c)
document.write('yes');
else
document.write('no');
To relate it to your example
searchMe = var1 && var2;
if(searchMe){
// this does work
}
精彩评论