用JS将字符串中的数字相乘

时间:2016-10-28 08:31:07

标签: javascript

我有这个字符串:

var sting = "500*500*500";

现在我想按字母顺序计算字符串中的数字。

如果我只是在字符串之外的数字我可以做数学如下:

var sum = 500*500*500;
console.log(sum) will return: 125000000

我发现了这个问题:
How to calculate numbers in string

有没有更简单的方法?
像:

var sum = calc(string);

2 个答案:

答案 0 :(得分:1)

最好的方法是使用Mathematic专用eval函数。

制作您自己的或只是使用真棒MathJS

// evaluate expressions
math.eval('sqrt(3^2 + 4^2)');           // 5
math.eval('sqrt(-4)');                  // 2i
math.eval('2 inch to cm');              // 5.08 cm
math.eval('cos(45 deg)');               // 0.7071067811865476

答案 1 :(得分:0)

您可以使用http://mathjs.org/ IE:

print(math.eval('500*500*500'));
相关问题