在没有eval的情况下在Javascript中的字符串中计算布尔表达式

dfj*_*dfj 6 javascript boolean-expression

我有一个包含布尔逻辑的字符串,类似于:

((true && true) || false && !true)
Run Code Online (Sandbox Code Playgroud)

在Javascript中安全地评估此字符串以获取布尔结果的最佳方法是什么?我想避免使用eval().

Ami*_*ein 0

您可以使用角度$parse服务。角度解析表达式,没有eval它们。

使用示例:

var x=$parse(' ((true && true) || false && !true) ')()
console.log(x)  // will return true
Run Code Online (Sandbox Code Playgroud)

阅读更多:

var x=$parse(' ((true && true) || false && !true) ')()
console.log(x)  // will return true
Run Code Online (Sandbox Code Playgroud)
var a=angular.module('app',[])
a.run(function($parse){
  alert($parse('true || false || true || false')())
  })
Run Code Online (Sandbox Code Playgroud)