简体   繁体   English

** IE11 不支持运算符。 如何使用代码用 Math.pow 替换它?

[英]** operator not supported in IE11. How to replace it with Math.pow using code?

I have this example formula:我有这个示例公式:

((97000 * ((5.50/100)/12)) / (1 - ((1 + ((5.50/100)/12))**(-1 * 120))))

The problem is that this code is not working correctly in IE11.问题是此代码在 IE11 中无法正常工作。 I have tried this method to replace each ** with Math.pow , but I cannot get it to work correctly:我已经尝试用这种方法用Math.pow替换每个** ,但我无法让它正常工作:

 function detectAndFixTrivialPow(expressionString) { var pattern = /(\\w+)\\*\\*(\\w+)/i; var fixed = expressionString.replace(pattern, 'Math.pow($1,$2)'); return fixed; } var expr = "((97000 * ((5.50/100)/12)) / (1 - ((1 + ((5.50/100)/12))**(-1 * 120))))"; var expr2 = detectAndFixTrivialPow(expr); console.log(expr); console.log(expr2); // no change...

Trying this with a regular expression is going to be tough.用正则表达式尝试这个会很困难。 Instead use a transpiler or at least an ECMAScript parser.而是使用转译器或至少使用 ECMAScript 解析器。

Here is an example how it can be done with the esprima parser.这是一个如何使用 esprima 解析器完成的示例。 This API produces an AST tree.这个 API 生成一个 AST 树。 The code below looks for the ** operator in that tree and collects the offsets where the input string should change.下面的代码在该树中查找**运算符并收集输入字符串应更改的偏移量。 Then these offsets are sorted in descending order to apply them in the right order to the input string.然后这些偏移量按降序排序,以正确的顺序将它们应用于输入字符串。

Note that this code does not attempt to save any parentheses.请注意,此代码不会尝试保存任何括号。 Those in the input are retained, and an extra pair is added for each of the Math.pow calls.保留输入中的那些,并为每个Math.pow调用添加一个额外的对。

 function convert(input) { let modifs = []; function recur(ast) { if (Object(ast) !== ast) return; // not an object if (ast.type === "BinaryExpression" && ast.operator == "**") { modifs.push( [ast.range[0], 0, "Math.pow("], [input.indexOf("**", ast.left.range[1]), 2, ","], [ast.range[1], 0, ")"] ); } Object.values(ast).forEach(recur); } recur(esprima.parse(expr, { range: true })); modifs.sort(([a], [b]) => b - a); let output = [...input]; for (let params of modifs) output.splice(...params); return output.join(""); } // Demo let expr = "((97000 * ((5.50/100)/12)) / (1 - ((1 + ((5.50/100)/12))**(-1 * 120))))" let result = convert(expr); console.log(result);
 <script src="https://cdn.jsdelivr.net/npm/esprima@4.0.1/dist/esprima.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM