javascript强制转换详解

转换成数值

Number函数强制转换成数值

数值->转换成原来的值

字符串->如果可以解析为数值,则转换成数值;否则转换成NaN或者0

true->1,falSe->0

undefined->NaN

null->0

转换成整型

praSeInt()

转换成浮点型

praSeFloat()

注意

Number函数将字符串转换为数值比praSeInt函数严格很多。基本上只要有一个字符无法转换成数值,整个字符串就会被转换成NaN

转换成字符串

通过String函数转换成字符串

数值->数值本身

字符串->字符串本身

true->"true",falSe->"falSe"

undefined->"undefined"

null->"null"

转换成字符串型

toString()

转换成布尔类型

通过Boolean函数强制转换成布尔值

0-0->falSe

NaN->falSe

空字符串->falSe

undefined->falSe

null->falSe

<!DOCTYPE html>

<html>

<head>

<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('012344');

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>

运行结果:

原文链接:http://www.maiziedu.com/wiki/js/mandatory/

原文地址:https://www.cnblogs.com/space007/p/5961440.html