Evaluating a string as a mathematical expression in JavaScript

前端 未结 16 2026
我在风中等你
我在风中等你 2020-11-22 03:34

How do I parse and evaluate a mathematical expression in a string (e.g. \'1+1\') without invoking eval(string) to yield its numerical value?

<
16条回答
  •  [愿得一人]
    2020-11-22 04:09

    You can do + or - easily:

    function addbits(s) {
      var total = 0,
          s = s.match(/[+\-]*(\.\d+|\d+(\.\d+)?)/g) || [];
          
      while (s.length) {
        total += parseFloat(s.shift());
      }
      return total;
    }
    
    var string = '1+23+4+5-30';
    console.log(
      addbits(string)
    )

    More complicated math makes eval more attractive- and certainly simpler to write.

提交回复
热议问题