数据类型转换:
1. 一般转换函数:
1) parseInt(参数): 将参数转换成整数. 返回值是整数格式的数值.
2) parseFloat(参数): 将参数转换成小数. 返回值是小数格式的数值.
参数要求:
[1] 参数内容格式需要符合数值格式的要求
[2] 参数格式中如果有不符合要求的部分, 则只将不符合部分之前内容进行转换
一般转换函数示例:
<script>
var str1 = "1990"
, str2 = "199.119"
, str3 = "199apple"
, str4 = "199.998apple"
, str5 = "apple1998";
document.write("str1:" + str1 + " >>> " + parseInt(str1) + "<br>");
document.write("str2:" + str2 + " >>> " + parseInt(str2) + "<br>");
document.write("str3:" + str3 + " >>> " + parseInt(str3) + "<br>");
document.write("str4:" + str4 + " >>> " + parseInt(str4) + "<br>");
document.write("str5:" + str5 + " >>> " + parseInt(str5) + "<br>");
document.write("<hr>");
document.write("str1:" + str1 + " >>> " + parseFloat(str1) + "<br>");
document.write("str2:" + str2 + " >>> " + parseFloat(str2) + "<br>");
document.write("str3:" + str3 + " >>> " + parseFloat(str3) + "<br>");
document.write("str4:" + str4 + " >>> " + parseFloat(str4) + "<br>");
document.write("str5:" + str5 + " >>> " + parseFloat(str5) + "<br>");
</script>
运行结果:
2. 强制转换函数:
1) Number(参数): 只要参数有任何不符合数值要求的部分, 结果都是NaN
2) Boolean(参数): 返回值 true/false
结果为false的情况:
数值: 0
字符串: ""
变量值为 null
变量未赋值
强制转换函数示例:
<script>
var str1 = "1990"
, str2 = "199.119"
, str3 = "199apple"
, str4 = "199.998apple"
, str5 = "apple1998";
document.write("str1:" + str1 + " >>> " + Number(str1) + "<br>");
document.write("str2:" + str2 + " >>> " + Number(str2) + "<br>");
document.write("str3:" + str3 + " >>> " + Number(str3) + "<br>");
document.write("str4:" + str4 + " >>> " + Number(str4) + "<br>");
document.write("str5:" + str5 + " >>> " + Number(str5) + "<br>");
document.write("<hr>");
var n1 = 10
, n2 = -10
, n3 = 0
, s1 = "false"
, s2 = ""
, v1 = null
, v2
, arr = []
, f1 = function (){}
, obj = {};
document.write("n1 : " + n1 + " >>> " + Boolean(n1) + "<br>");
document.write("n2 : " + n2 + " >>> " + Boolean(n2) + "<br>");
document.write("n3 : " + n3 + " >>> " + Boolean(n3) + "<br>");
document.write("s1 : " + s1 + " >>> " + Boolean(s1) + "<br>");
document.write("s2 : " + s2 + " >>> " + Boolean(s2) + "<br>");
document.write("v1 : " + v1 + " >>> " + Boolean(v1) + "<br>");
document.write("v2 : " + v2 + " >>> " + Boolean(v2) + "<br>");
document.write("arr : " + arr + " >>> " + Boolean(arr) + "<br>");
document.write("f1 : " + f1 + " >>> " + Boolean(f1) + "<br>");
document.write("obj : " + obj + " >>> " + Boolean(obj) + "<br>");
</script>
运行结果:
3. 判断数据是否不符合数值格式: isNaN(参数), 返回true表示参数不符合数值格式要求