简体   繁体   English

在javascript中解析数字比较字符串

[英]parsing a number comparison string in javascript

So I'm wondering if there is a simple method for, i guess, parsing a string that contains a number comparison.所以我想知道是否有一种简单的方法可以解析包含数字比较的字符串。

For example I have a variable that contains a string like this str = "1>3";例如,我有一个变量,其中包含这样的字符串str = "1>3";

Right now I'm using the math plugin to use math.eval(str) which returns a boolean but I feel like this is an awfully big resource to include just for a simple comparison.现在我正在使用数学插件来使用 math.eval(str) ,它返回一个布尔值,但我觉得这是一个非常大的资源,仅用于简单的比较。

My script is currently like this, and I love the simplicity I just hate having to use such a big resource for it.我的脚本目前是这样的,我喜欢它的简单性,我只是讨厌不得不为此使用如此大的资源。

if (math.eval(str) == true) {
    //do something
} else {
   // do something else
}

Any input on this matter would be greatly appreciated.对此问题的任何意见将不胜感激。 I thank you in advance.我提前谢谢你。

If you need that for friendly environment (non-public, no security considerations) you can use regular eval to compute result:如果您需要友好环境(非公开,没有安全考虑),您可以使用常规eval来计算结果:

var result = eval("1>3");

Note that eval let you run any code and if you let user enter the "condition" and plan to use that for anything outside of personal calculator sample on you local machine - use proper parser that validates expressions and does not use arbitrary functions.请注意, eval允许您运行任何代码,如果您让用户输入“条件”并计划将其用于本地计算机上个人计算器示例之外的任何内容 - 使用正确的解析器来验证表达式并且不使用任意函数。

If you have such simple expressions, like如果你有这么简单的表达,比如

 expression := number comparison_operator number
 comparison_operator := < | > | = | ..

then it is also very simple to write a parser for this.那么为此编写一个解析器也很简单。

Eg split the input string along the operator,例如,沿运算符拆分输入字符串,

"1>3" -> 
op = ">" ->
split: ["1", "3"] -> 
num1_str = "1", num2_str = "3"

convert each number from its string representation to a number value.将每个数字从其字符串表示形式转换为数字值。

num1 = 1, num2 = 3

Then apply the comparison operator.然后应用比较运算符。

switch (op) {
case "<":
  return num1 < num2;
case ">":
  return num1 > num2;
case "=":
  return num1 == num2;
// <=, >=, !=, ..
default:
  // unknown operator
}

这个库为表达式解析做了很多开箱即用的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM