javascript 如何在javascript中将String变量转换为int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12040769/
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-10-26 15:08:27  来源:igfitidea点击:

How to convert String variable to int in javascript?

javascriptstringinttype-conversionnumeric

提问by Sami

What is the correct way to convert value of String variable to int/numeric variable? Why is bcIntstill string and why does isNaNreturn true?

将 String 变量的值转换为 int/numeric 变量的正确方法是什么?为什么bcInt仍然是字符串,为什么isNaN返回true

bc=localStorage.getItem('bc');
var bcInt=parseInt(bc,10);
var bcInt2=1;
console.log("bc------------>" +bc +" isNaN:" +isNaN(bc)); //isNaN returns true
console.log("bcInt------------>" +bcInt +" isNaN:" +isNaN(bcInt)); //isNaN returns true

bcInt2// isNaN returns false

回答by Florian Margaine

parseIntreturns a number only if you pass it a number as first character.

parseInt仅当您将数字作为第一个字符传递给它时才返回数字。

Examples:

例子:

parseInt( 'a', 10 ); // NaN
parseInt( 'a10', 10 ); // NaN
parseInt( '10a', 10 ); // 10
parseInt( '', 10 ); // NaN
parseInt( '10', 10 ); // 10

Also, you may take a look at the +operator if you want to get strings that are only numbers.

此外,+如果您想获取只有数字的字符串,您可以查看运算符。

+'a'; // NaN
+'a10'; // NaN
+'10a'; // NaN
+''; // 0, that's tricky
+'10'; // 10

Edit: According to your comment, I've tested parseInt:

编辑:根据您的评论,我已经测试过parseInt

parseInt( '08-20 19:41:02.880', 10 ); // 8

You're doing something else wrong. parseIntreturns everything till it's not a number. If the first isn't a number (or it doesn't find any number), it returns NaN.

你做错了其他事情。parseInt返回所有内容,直到它不是数字。如果第一个不是数字(或找不到任何数字),则返回NaN.

回答by Sami

The answer is that I used localStorage.setItem('bc',JSON.stringify(bc))and it added double quote to bcbecause it was in that case already a string and that's why parseIntwasn't working. Value was ""1"".

答案是我使用localStorage.setItem('bc',JSON.stringify(bc))并添加了双引号,bc因为在那种情况下它已经是一个字符串,这就是为什么parseInt不起作用。价值是""1""