轉換成數值
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/