簡體   English   中英

操作員在嚴格模式下更換“with”

[英]Operator replacement “with” in strict mode

我有輸入用戶的字符串值,例如變量f。

f = "1/log(x)";

在vanilla JavaScript中,我使用了運算符:

f = "with (Math) {" + f + "}";

代碼在vanilla javascript中非常出色,但是我使用Vue js並且在嚴格模式下遇到問題。 我不知道如何更換此運算符。 誰遇到這個問題請回答我。

我試試這個:

            let math = Math
            math.f = f
            console.log(f)

但沒有任何效果。

基本上不推薦使用,因為它可能會導致程序出現問題。 那么你有什么選擇呢?

定義一堆全局變量

 const sqrt = Math.sqrt const log = Math.log const test1 = new Function("a","return sqrt(a)") const test2 = new Function("b","return log(b)") console.log(test1(4)) console.log(test2(100)) 

其他選擇是使用reg exp進行替換

 const fixMath = eq => eq.replace(/(sqrt|log|pow)/g,'Math.$1') const test1 = new Function("a", fixMath("return sqrt(a)")) const test2 = new Function("b", fixMath("return log(b)")) const test3 = new Function("a", "b", fixMath("return pow(a, b)")) const test4 = new Function("a", "b", fixMath("return sqrt(pow(a, 2) + pow(b, 2))")) console.log(test1(4)) console.log(test2(100)) console.log(test3(10, 3)) console.log(test4(3, 3)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM