问题
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()
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)
}
Is there any possible way of replacing eval()
with something else to answer a string like question.text
?
回答1:
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())
回答2:
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;
}
来源:https://stackoverflow.com/questions/32982719/chrome-app-doing-maths-from-a-string