天天看点

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>

运行结果:

javascript强制转换详解

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

继续阅读