** IE11 不支持运算符.如何使用代码将其替换为 Math.pow? [英] ** operator not supported in IE11. How to replace it with Math.pow using code?

查看:26
本文介绍了** IE11 不支持运算符.如何使用代码将其替换为 Math.pow?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个示例公式:

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

问题是此代码在 IE11 中无法正常工作.我已经尝试用这种方法将每个 ** 替换为 Math.pow,但我无法让它正常工作:

The problem is that this code is not working correctly in IE11. I have tried this method to replace each ** with Math.pow, but I cannot get it to work correctly:

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 解析器.

Trying this with a regular expression is going to be tough. Instead use a transpiler or at least an ECMAScript parser.

这是一个如何使用 esprima 解析器完成的示例.这个 API 生成一个 AST 树.下面的代码在该树中查找 ** 运算符并收集输入字符串应更改的偏移量.然后这些偏移量按降序排列,以正确的顺序将它们应用到输入字符串中.

Here is an example how it can be done with the esprima parser. This API produces an AST tree. 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.

请注意,此代码不会尝试保存任何括号.保留输入中的那些,并为每个 Math.pow 调用添加额外的一对.

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.

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>

这篇关于** IE11 不支持运算符.如何使用代码将其替换为 Math.pow?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆