I'm needing to create a dynamic validator based on a string value that's passed into a json object. So let's say you have the following string:
var required: "Homes > 0"
In this example, "Homes" is an accessible object within my function. I want to logically turn the above into:
if (this.Homes > 0) { return true; }
Thinking about this in parts:
if (this[left] > parsed[right]) { return true; }
I think you get the idea. I'm not sure if there's a way to easily extract operators without just doing a switch for every type? As in:
required: "Homes = 0" // this[Left] === 0
I'm about to do this in a very horrifying ugly string splitting way with a switch case on the operators. Was just wondering if there was a super slick way to make something like this robust.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
eval('Homes > 0');
but please consider using this pattern instead:
function Class(){
this.validate = function(){
return true;
}
}
var x = new Class();
//overload the validate operator
x.validate = function(){
return false;
}
You want to avoid eval because it is potentially unsafe because it allows for arbitrary code execution.
尝试使用
eval("if (this.Homes > 0) { return true; }");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.