Eval alternative

前端 未结 4 1652
-上瘾入骨i
-上瘾入骨i 2020-12-20 05:13

This code works as a calculator, but the scratch pad at codeacademy tells me that eval is evil. Is there another way to do the same thing without using eval?



        
4条回答
  •  太阳男子
    2020-12-20 05:21

    You can use the expression parser that is included in the math.js library:

    http://mathjs.org

    Example usage:

    mathjs.evaluate('1.2 / (2.3 + 0.7)');   // 0.4
    mathjs.evaluate('5.08 cm in inch');     // 2 inch
    mathjs.evaluate('sin(45 deg) ^ 2');     // 0.5
    mathjs.evaluate('9 / 3 + 2i');          // 3 + 2i
    mathjs.evaluate('det([-1, 2; 3, 1])');  // -7
    

提交回复
热议问题