简体   繁体   English

IE11 的 Math.pow 替代“**”ES7 polyfill

[英]Math.pow alternative "**" ES7 polyfill for IE11

I'm trying to evaluate an expression which contains power, in string as ** .我正在尝试评估一个包含幂的表达式,在字符串中为** ie eval("(22**3)/12*6+3/2") .The problem is Internet Explorer 11 does not recognizes this and throws syntax error.eval("(22**3)/12*6+3/2") 。问题是 Internet Explorer 11 无法识别这一点并引发语法错误。 Which poly-fill I should use to overcome this?我应该使用哪种填充物来克服这个问题? Right now I'm using Modernizr 2.6.2 .现在我正在使用Modernizr 2.6.2

example equation would be,示例方程是,

((1*2)*((3*(4*5)*(1+3)**(4*5))/((1+3)**(4*5)-1)-1)/6)/7
((1*2)*((3*(4*5)*(1+3)**(4*5))/((1+3)**(4*5)-1)-1)/6)/7*58+2*5
(4*5+4-5.5*5.21+14*36**2+69/0.258+2)/(12+65)

If it is not possible to do this, what are the possible alternatives?如果无法做到这一点,有哪些可能的替代方案?

You cannot polyfill operators - only library members (prototypes, constructors, properties).您不能 polyfill 运算符 - 只有库成员(原型、构造函数、属性)。

As your operation is confined to an eval call, you could attempt to write your own expression parser, but that would be a lot of work.由于您的操作仅限于eval调用,您可以尝试编写自己的表达式解析器,但这将是很多工作。

(As an aside, you shouldn't be using eval anyway, for very good reasons that I won't get into in this posting). (顺便说一句,无论如何你都不应该使用eval ,因为我不会在这篇文章中讨论这个很好的理由)。

Another (hack-ish) option is to use a regular expression to identify trivial cases of x**y and convert them to Math.pow :另一个(hack-ish)选项是使用正则表达式来识别x**y的琐碎情况并将它们转换为Math.pow

function detectAndFixTrivialPow( expressionString ) {

    var pattern = /(\w+)\*\*(\w+)/i;

    var fixed = expressionString.replace( pattern, 'Math.pow($1,$2)' );
    return fixed;
}

eval( detectAndFixTrivialPow( "foo**bar" ) );

You can use a regular expression to replace the occurrences of ** with Math.pow() invocations:您可以使用正则表达式将出现的**替换为Math.pow()调用:

 let expression = "(22**3)/12*6+3/2" let processed = expression.replace(/(\w+)\*\*(\w+)/g, 'Math.pow($1,$2)'); console.log(processed); console.log(eval(processed));

Things might get complicated if you start using nested or chained power expressions though.但是,如果您开始使用嵌套或链接的幂表达式,事情可能会变得复杂。

I think you need to do some preprocessing of the input.我认为您需要对输入进行一些预处理。 Here is how i would approach this:这是我将如何处理这个问题:

  1. Find "**" in string.在字符串中查找“**”。
  2. Check what is on the left and right.检查左侧和右侧的内容。
  3. Extract "full expressions" from left and right - if there is just a number - take it as is, and if there is a bracket - find the matching one and take whatever is inside as an expression.从左右提取“完整表达式” - 如果只有一个数字 - 按原样处理,如果有括号 - 找到匹配的一个并将里面的任何内容作为表达式。
  4. Replace the 2 expressions with Math.pow(left, right)用 Math.pow(left, right) 替换 2 个表达式

您可以在线使用 Babel为 IE 11 转换 javascript。

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

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