Chrome App: Doing maths from a string

天涯浪子 提交于 2019-11-27 15:55:52

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())

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!