JavaScript类型转换—强制转换
显示转换
一 转换成布尔类型【通过Boolean函数转换成布尔值】
1.0,-0,0.0->false
2.NaN->false
3.空字符串->false
4.undefined->false
5.null->false
二 转换成字符串
1.通过String函数转换成字符串
1)数值->数值本身
2)字符串->字符串本身
3)true->“true” false->“false”
4) undefined->“undefined”
5) null->“null”
2.toString转换成字符串型
三 转换成数值
1.Number函数强制转换成数值
1)数值->转换成原来的值
2)字符串->如果可以解析为数值,则转换成数值;否则转换成NaN或者0
3)true->1,false->0
4) undefined->NaN
5) null->“0”
2.转换成整型【parseInt(string,radix):返回值转换成整数的值】
注意:
1)当参数radix的值为0,或者没有设置这个参数,parseInt()会根据string来判断数字的基数;
2)当忽略radix,javascript默认数字的基数规则为
a.如果string以0x开头,parseInt()会把string的其余部分解析为十六进制的整数
b.如果string以0开头,那么ECMAScript v3允许
parseInt()的一个实现把其后的字符解析为八进制或十六进制的数字
c.如果string以1-9的数字开头,parseInt()将把它解析为十进制的整数
d.字符串如果以合法字符开始,截取合法字符
e.开头和结尾的空格是允许的
f.如果字符串的第一个字符不能转换为数字,parseInt()会返回NaN
g.在字符串以“0”为开始时旧的浏览器默认使用八进制数。ECMAScript 5,默认的是十进制的基数。
3.转换成浮点型【parseFloat(string):返回转换成浮点型的值】
该函数指定字符串中的首个字符是否是数字。如果是。则对字符串进行解析,直到到达数字的末端为止,然后以数字返回该数字,而不是字符串。
注意 :
Number函数将字符串转换为数值比parseInt函数严格很多。基本上只要有一个字符无法转换成数值,整个字符串就会被转换成NaN
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
//其他类型转换成布尔类型false的有
var test=Boolean(0);
test=Boolean(-0);
test=Boolean(NaN);
test=Boolean(undefined);
test=Boolean('');
test=Boolean(0.0);
test=Boolean('0');
//其他类型转换成字符串型
test=String(1234);
test=String(23.34);
test=String('this is a test');
test=String(true);
test=String(false);
test=String(null);
test=String(undefined);
test=String(NaN);
//其他类型转换成数值型
test=Number(12);
test=Number(232.3);
test=Number(true);
test=Number(false);
test=Number(undefined);
test=Number(NaN);
test=Number(null);
test=Number('3king');
test=Number('324');
//通过parseInt()进行转换成整型
test=parseInt('123');
test=parseInt('234',0);
test=parseInt('0xabcdef');
test=parseInt(45,16);
test=parseInt('3ki23ng');
test=parseInt('true');
test=parseInt(true);
test=parseInt('35 6 a');
//通过parseFloat()转换成浮点型
test=parseFloat('123.34abc');
test=parseFloat('123');
test=parseFloat('sdf');
test=parseFloat('2e3a');
alert(test);
</script>
</head>
<body>
<h1>强制转换的例子</h1>
</body>
</html>