如何在javascript中将String变量转换为int? [英] How to convert String variable to int in javascript?

查看:1038
本文介绍了如何在javascript中将String变量转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the correct way to convert value of String variable to int/numeric variable? Why is bcInt still string and why does isNaN return 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


推荐答案

parseInt 只有在您将数字作为第一个字符传递时才返回一个数字。

parseInt returns a number only if you pass it a number as first character.

示例:

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

编辑:根据你的评论,我测试了 parseInt

According to your comment, I've tested parseInt:

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

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

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

这篇关于如何在javascript中将String变量转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆