Chrome App: Doing maths from a string

前端 未结 2 1091
情书的邮戳
情书的邮戳 2020-12-04 01:37

I have a basic Chrome App that I\'m building that constructs strings like this:

\"1 + 4 - 3 + -2\"

Seeing as you can\'t use eval()

2条回答
  •  再見小時候
    2020-12-04 01:58

    Try modifying string to

    "+1 +4 -3 -2"
    

    utilizing String.prototype.split() , Array.prototype.reduce() , Number()

    var question = {
      text: "+1 +4 -3 -2",
      answer: function() {
                return this.text.split(" ")
                       .reduce(function(n, m) {
                         return Number(n) + Number(m)
                       })
              }
    };
    
    console.log(question.answer())

提交回复
热议问题