简体   繁体   English

将字符串转换为数字

[英]Convert string to number

I have some simple variables whose values are numeric strings: 我有一些简单的变量,其值为数字字符串:

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

I want to turn s into 1000 and v to 600 . 我想将s变成1000 ,将v变成600

Use eval() function: 使用eval()函数:

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

If the strings are from a truly trusted source, you can use eval to do that: 如果字符串来自真正可信的来源,则可以使用eval进行操作:

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

But note that eval fires up a JavaScript parser, parses the given string, and executes it. 但是请注意, eval会启动JavaScript解析器,解析给定的字符串,然后执行它。 If there's any chance that the given string may not be from a trusted source, you don't want to use it, as you're giving the source the ability to arbitrarily execute code. 如果给定的字符串有可能不是来自受信任的源,则您不想使用它,因为您可以使源具有任意执行代码的能力。

If you can't trust the source, then you'll have to parse the string yourself. 如果您不信任源,则必须自己解析该字符串。 Your specific examples are easy, but I'm sure your actual need is more complex. 您的具体示例很简单,但是我确信您的实际需求更加复杂。

The dead easy bit: 容易的死法:

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);
}

...but again, I'm sure your actual requirement is more complex — other operators, spaces around the values, parentheses, etc. ...但是再次,我确定您的实际要求更加复杂-其他运算符,值周围的空格,括号等。


Picking up on Andy E's comment below, whitelisting might well be a way to go: 采纳以下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 现场例子

That regexp may not be perfect, I'd stare at it long and hard before I'd let any unwashed input head its way... 该regexp可能并不完美,在让任何未清洗的输入前进之前,我会凝视它很长时间。

this could be achieved quite simply without resorting to 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")) 

You can use the eval function to evaluate an expression in a string: 您可以使用eval函数来评估字符串中的表达式:

var evaluated = eval(s);

alert(evaluated) will then alert 1000 . alert(evaluated)将提醒1000

If you "just" want to have these numbers out of the string you can do 如果您只是想将这些数字从字符串中删除,则可以这样做

eval(s)

to get "10*10*10" as a Number 得到“ 10 * 10 * 10”作为数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM