Chrome App: Doing maths from a string

前端 未结 2 1077
情书的邮戳
情书的邮戳 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:47

    Try this

    var question = {
      text: "1 + 4 - 3 + -2",
      answer: eval(ans(question.text))
    }
    console.log('Text : '+question.text);
    console.log('answer : '+question.answer);
    

    Used String replace method

    function ans(str){
    var s = str.replace(/\s/g, '')
    console.log('S : '+s);
    return s;
    }
    
    0 讨论(0)
  • 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())

    0 讨论(0)
提交回复
热议问题