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

时间:2021-02-19 22:01:49

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

我正在尝试将req.params转换为Number,因为这是我在我的架构中为年份参数定义的。

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?

但他们没有工作。我需要安装一些东西吗?

1 个解决方案

#1


65  

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,你的输出是什么?它仍然是一个字符串?

#1


65  

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,你的输出是什么?它仍然是一个字符串?