如何在javascript中将字符串转换为数学运算符 [英] How can I convert a string into a math operator in javascript
问题描述
如果我有一个数学方程式的字符串,我想将其拆分然后进行计算。我知道我可以使用eval()函数来做到这一点,但我很感兴趣,如果有另一种方法可以做到这一点 - 特别是首先拆分字符串。所以我有类似的东西
If I've got a string that is a mathematic equation and I want to split it and then calculate it. I know I can use the eval() function to do this, but I'm interested if there's an alternative way to do this - specifically by splitting the strings first. So I've got something like
var myString = "225 + 15 - 10"
var newString = myString.split(" ");
这会将myString变成一个数组:[225,+,15, - ,10];
This would turn myString into an array: ["225", "+", "15", "-", "10"];
我的下一个任务是将所有奇数编号的字符串转换成整数,我想我可以使用parseInt();对于。我的问题是,如何将+和 - 转换为实际的算术运算符?所以最后我留下了一个我可以计算的数学表达式?
My next task is to turn all the odd-numbered strings into integers, which I think I could use parseInt(); for. My question is, how do I turn the "+" and "-" into actual arithmetic operators? So that at the end I am left with a mathematic expression which I can calculate?
这可能吗?
推荐答案
var math_it_up = {
'+': function (x, y) { return x + y },
'-': function (x, y) { return x - y }
};
math_it_up['+'](1, 2) == 3;
这篇关于如何在javascript中将字符串转换为数学运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!