将字符串转换为数字 node.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37271445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:12:51  来源:igfitidea点击:

convert string to number node.js

node.jsstringtype-conversion

提问by user3488862

I'm trying to convert req.params to Number because that is what I defined in my schema for year param.

我正在尝试将 req.params 转换为 Number,因为这是我在我的模式中为 year param 定义的。

I have tried

我试过了

req.params.year = parseInt( req.params.year, 10 );  

and

Number( req.params.year);

and

1*req.params.year;

but non of them works. Do I need to install something?

但没有一个有效。我需要安装什么吗?

回答by Tusk

You do not have to install something.

您不必安装某些东西。

parseInt(req.params.year, 10);

should work properly.

应该可以正常工作。

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

如果您使用 parseInt,您的输出是什么?它仍然是一个字符串吗?

回答by tejp124

Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.

使用 parseInt() 是一个坏主意,主要是因为它永远不会失败。还因为某些结果可能出乎意料,例如 INFINITY。
下面是处理意外行为的函数。

function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);
}

See results of below test cases.

查看以下测试用例的结果。

console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));

result:

结果:

CleanInt:  NaN  ParseInt:  NaN
CleanInt:  NaN  ParseInt:  123
CleanInt:  234  ParseInt:  234
CleanInt:  -679  ParseInt:  -679
CleanInt:  897  ParseInt:  897
CleanInt:  Infinity  ParseInt:  NaN

回答by Werlious

Not a full answerOk so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

不是一个完整的答案好的,所以这只是补充有关 parseInt 的信息,它仍然非常有效。Express 根本不允许修改 req 或 res 对象(不可变)。所以如果你想有效地修改/使用这些数据,你必须将它复制到另一个变量(var year = req.params.year)。