在javascript中中可以使用Number()方法或parseInt()方法来将字符串转换为整数。
方法1:使用Number()方法
Number() 函数把对象的值转换为数字;如果对象的值无法转换为数字,那么 Number() 函数返回 NaN。
示例:
<script type="text/javascript">
var test1= new Boolean(true);
var test2= new Boolean(false);
var test3= new String("999");
var test4= new String("999 888");
document.write(Number(test1)+ "<br />");
document.write(Number(test2)+ "<br />");
document.write(Number(test3)+ "<br />");
document.write(Number(test4)+ "<br />");
</script>
//输出
1
0
999
NaN方法2:使用parseInt()方法
parseInt() 函数可解析一个字符串,并返回一个整数。
var test= new String("999");
typeof parseInt(test)
//输出
number如果字符串的第一个字符不能被转换为数字,那么parseInt()会返回 NaN。
示例:
<script type="text/javascript">
var test1= new String("1");
var test2= new String("2");
var test3= new Boolean(true);
console.log(parseInt(test1));
console.log(parseInt(test2));
console.log(parseInt(test3));
</script>
//输出
1
2
NaN 



网友评论文明上网理性发言 已有0人参与
发表评论: