簡體   English   中英

** IE11 不支持運算符。 如何使用代碼用 Math.pow 替換它?

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

我有這個示例公式:

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

問題是此代碼在 IE11 中無法正常工作。 我已經嘗試用這種方法用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...

用正則表達式嘗試這個會很困難。 而是使用轉譯器或至少使用 ECMAScript 解析器。

這是一個如何使用 esprima 解析器完成的示例。 這個 API 生成一個 AST 樹。 下面的代碼在該樹中查找**運算符並收集輸入字符串應更改的偏移量。 然后這些偏移量按降序排序,以正確的順序將它們應用於輸入字符串。

請注意,此代碼不會嘗試保存任何括號。 保留輸入中的那些,並為每個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