是否可以将数组值转换/包装到 if 语句中?为了澄清起见,我从代码中收到的语句始终是数组中的字符串,并且我想在 if 块中执行它。现在,它不进行比较,因为它是一个字符串。那么如何将字符串转换为要进行比较的语句呢?
let counter = 11;
let statement = ['counter > 10']; // array string received from other code (always a string)
if(statement[0]) {
// should be true
}
结果预期为 true,其中 if 语句是动态执行的。
let counter = 11;
let statement = ['counter > 10']; // (always a string)
if (eval(statement[0])) {
console.log("The statement is true");
} else {
console.log("The statement is false");
}
我认为提出这个问题的更好方法是“如何像 JavaScript 代码一样计算字符串。有一种方法可以在 JavaScript 中使用
eval
方法来完成此操作。
let counter = 11;
let statement = ['counter > 10']; // (always a string)
if (eval(statement[0])) {
// should be true
}
但是,我真的不建议使用这个。这是一个巨大的安全风险。仅当您知道自己在做什么时才使用它。
您也许可以使用数学解析器来实现此目的,但我不确定。这取决于你在该字符串中得到什么样的东西。
// https://github.com/silentmatt/expr-eval/tree/master
// there may be other ways to do this, this is simple though
import Parser from 'expr-eval';
const options = {x:3}; //see the documentation
const parsedStatement = statement[0];
const result = Parser.evaluate(parsedStatement, {options});
console.debug('Expression Result: ', result);