将字符串转换为数字

时间:2011-06-15 09:46:44

标签: javascript

我有一些简单的变量,其值是数字字符串:

var s = '10*10*10',
    v = '60*10';

我想将s变为1000,将v变为600

5 个答案:

答案 0 :(得分:7)

使用eval()功能:

var result = eval('10*10*10');
alert(result); // alerts 1000

答案 1 :(得分:7)

如果 字符串来自真正受信任的来源,您可以使用eval来执行此操作:

var s = '10*10*10';
var result = eval(s);

但是请注意eval会启动JavaScript解析器,解析给定的字符串并执行它。如果给定字符串可能不是来自可靠来源,您不希望使用它,因为您可以让源能够任意执行代码。

如果您不能信任源,那么您必须自己解析字符串。您的具体示例很简单,但我确信您的实际需求更加复杂。

死的简单:

var s, operands, result, index;
s = '10*10*10';
operands = s.split('*');
result = parseInt(operands[0], 10); 
for (index = 1; index < operands.length; ++index) {
    result *= parseInt(operands[index], 10);
}

...但是,我确定你的实际要求更复杂 - 其他运算符,值周围的空格,括号等。


在下面提到Andy E的评论,白名单可能是一种可行的方式:

function doTheMath(s) {
    if (!/^[0-9.+\-*\/%() ]+$/.test(s)) {
        throw "Invalid input";
    }
    return eval('(' + s + ')');
}
var result = doTheMath('10*10*10');               // 1000
var result2 = doTheMath('myEvilFunctionCall();'); // Throws exception

Live example

那个正则表达可能并不完美,在我让任何未经洗涤的输入结束之前,我会长时间地盯着它......

答案 2 :(得分:1)

这可以很简单地实现而不需要使用eval

function calc(s) {

   s = s.replace(/(\d+)([*/])(\d+)/g, function() {
        switch(arguments[2]) {
            case '*': return arguments[1] * arguments[3];
            case '/': return arguments[1] / arguments[3];
        }
   })

   s = s.replace(/(\d+)([+-])(\d+)/g, function() {
        switch(arguments[2]) {
            case '+': return parseInt(arguments[1]) + parseInt(arguments[3]);
            case '-': return arguments[1] - arguments[3];
        }
   })

   return parseInt(s);

}

alert(calc("10+5*4")) 

答案 3 :(得分:0)

您可以使用eval函数来评估字符串中的表达式:

var evaluated = eval(s);

然后

alert(evaluated)会提醒1000

答案 4 :(得分:0)

如果您“只是”希望将这些数字从字符串中删除,那么

eval(s)

将“10 * 10 * 10”作为数字

相关问题