Chrome 应用:根据字符串进行数学计算
Chrome App: Doing maths from a string
我有一个基本的 Chrome 应用程序,我正在构建它构建这样的字符串:
"1 + 4 - 3 + -2"
既然你不能在 Chrome 应用程序中使用 eval()
,我怎样才能得到像这样的字符串的答案?
例如。如果这只是一个普通的网页,我会使用这样的东西:
var question = {
text: "1 + 4 - 3 + -2",
answer: eval(this.text)
}
是否有任何可能的方法将 eval()
替换为其他内容以回答像 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())
试试这个
var question = {
text: "1 + 4 - 3 + -2",
answer: eval(ans(question.text))
}
console.log('Text : '+question.text);
console.log('answer : '+question.answer);
使用字符串替换方法
function ans(str){
var s = str.replace(/\s/g, '')
console.log('S : '+s);
return s;
}
我有一个基本的 Chrome 应用程序,我正在构建它构建这样的字符串:
"1 + 4 - 3 + -2"
既然你不能在 Chrome 应用程序中使用 eval()
,我怎样才能得到像这样的字符串的答案?
例如。如果这只是一个普通的网页,我会使用这样的东西:
var question = {
text: "1 + 4 - 3 + -2",
answer: eval(this.text)
}
是否有任何可能的方法将 eval()
替换为其他内容以回答像 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())
试试这个
var question = {
text: "1 + 4 - 3 + -2",
answer: eval(ans(question.text))
}
console.log('Text : '+question.text);
console.log('answer : '+question.answer);
使用字符串替换方法
function ans(str){
var s = str.replace(/\s/g, '')
console.log('S : '+s);
return s;
}