如何将字符串转换为布尔值?

问题描述 投票:0回答:3

是否可以将数组值转换/包装到 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 语句是动态执行的。

javascript
3个回答
0
投票
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");
}

0
投票

我认为提出这个问题的更好方法是“如何像 JavaScript 代码一样计算字符串。有一种方法可以在 JavaScript 中使用

eval
方法来完成此操作。

let counter = 11;
let statement = ['counter > 10']; // (always a string)

if (eval(statement[0])) {
      // should be true
}

但是,我真的不建议使用这个。这是一个巨大的安全风险。仅当您知道自己在做什么时才使用它。

参考:https://www.w3schools.com/jsref/jsref_eval.asp


0
投票

您也许可以使用数学解析器来实现此目的,但我不确定。这取决于你在该字符串中得到什么样的东西。

// 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);

© www.soinside.com 2019 - 2024. All rights reserved.