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

Sam*_*ami 3 javascript string int numeric type-conversion

将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
Run Code Online (Sandbox Code Playgroud)

Flo*_*ine 8

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

例子:

parseInt( 'a', 10 ); // NaN
parseInt( 'a10', 10 ); // NaN
parseInt( '10a', 10 ); // 10
parseInt( '', 10 ); // NaN
parseInt( '10', 10 ); // 10
Run Code Online (Sandbox Code Playgroud)

此外,+如果您想获得仅为数字的字符串,您可以查看运算符.

+'a'; // NaN
+'a10'; // NaN
+'10a'; // NaN
+''; // 0, that's tricky
+'10'; // 10
Run Code Online (Sandbox Code Playgroud)

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

parseInt( '08-20 19:41:02.880', 10 ); // 8
Run Code Online (Sandbox Code Playgroud)

你做错了什么.parseInt返回一切,直到它不是一个数字.如果第一个不是数字(或者没有找到任何数字),则返回NaN.