Chrome应用程序:从字符串中进行数学运算 [英] Chrome App: Doing maths from a string

查看:162
本文介绍了Chrome应用程序:从字符串中进行数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的Chrome应用程序,我正在构建这样构造字符串:

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

"1 + 4 - 3 + -2"

因为你不能使用 eval()在Chrome应用中,如何获得类似字符串的答案?

Seeing as you can't use eval() in Chrome Apps, how can I get the answer to a string like so?

例如。如果这只是一个普通的网页,我会使用这样的东西:

eg. If this was just a normal webpage I would use something like this:

var question = {
  text: "1 + 4 - 3 + -2",
  answer: eval(this.text)
}

是否有任何可能的方法用其他东西替换 eval()来回答像 question.text

Is there any possible way of replacing eval() with something else to answer a string like question.text?

推荐答案

尝试将字符串修改为

"+1 +4 -3 -2"

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

这篇关于Chrome应用程序:从字符串中进行数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆