简体   繁体   English

操作员在严格模式下更换“with”

[英]Operator replacement “with” in strict mode

I have string value which entered user, for example the variable f. 我有输入用户的字符串值,例如变量f。

f = "1/log(x)";

In vanilla JavaScript, i used operator with: 在vanilla JavaScript中,我使用了运算符:

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

The code work excellent in vanilla javascript, but i use Vue js and have problems in strict mode. 代码在vanilla javascript中非常出色,但是我使用Vue js并且在严格模式下遇到问题。 I don't know how replace this operator. 我不知道如何更换此运算符。 Who faced with this problem please answer me. 谁遇到这个问题请回答我。

I try this: 我试试这个:

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

But nothing working. 但没有任何效果。

Basically with is not recommended to be used because it can cause issues in programs. 基本上不推荐使用,因为它可能会导致程序出现问题。 So what are your options? 那么你有什么选择呢?

define a bunch of globals 定义一堆全局变量

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

Other option is to do the replacements with a reg exp 其他选择是使用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