如何将数组值包装到if块中?

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

是否可以将数组值转换/包装到 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
1个回答
0
投票
let statement = ['counter > 10'];  (always a string)

if (eval(statement[0])) {
    console.log("The statement is true");
} else {
    console.log("The statement is false");
}
© www.soinside.com 2019 - 2024. All rights reserved.