1.undefined 的转化问题
(1).转为字符串
undefined会被自动转换成字符串"undefined";
var test = undefined + "";
undefined = "test";
alert(undefined); //undefined将被定义成字符串"test"
(2).转成数字
undefined在数字场合将被转换成NaN
var test = undefined - 0;
alert(test) //将打印出'NaN',其实这里数字NaN又被转换成了字符串'NaN'
(3).转成布尔
undefined在布尔类型的场合将被转换成false
var test;
if(!test) //判断为true
{
test = "test";
}
(4).转成对象
undefined在对象场合会转换成Error对象
2.null 的转化问题
null基本与undefined相同,它是JavaScript的关键字,但仍有部分不同之处:
var test;
alert(null == test); //true
alert(null == undefined); //true
(1).转成字符串
null在字符串场合被转换成字符串"null"
alert(null+"ss"); //将打印出"nullss"
(2).转成数字
null在数字场合被转换成 0
var test = null+5;
alert(test); //5
(3).转成布尔型
null同undefined一样,在需要进行布尔运算时,会被转换成false
if(null)
{
alert("null");
}
else
{
alert("is not null");
}//输出 is not null
(4).转成对象
null在对象环境中被转换成 Error 对象。
3.非空字符串的转化问题
(1).转成数字
非空字符串能被动态的转换成对应的数值或者NaN
var x = "55" - 3 //51
var y = "ab" - 3 //NaN(Not a Number)
或者使用Global的parseFloat()或者parseInt()方法,可以进行isNaN()来检查parseInt()和parseFloat()方法的返回值是否等于NaN的布尔值。
var x = "123";
var y = "abc";
alert(parseInt(x)); //123
alert(parseInt(y)); //NaN
alert(isNaN(parseInt(x))); //false
alert(isNaN(parseInt(y))); //true (检测到返回值等于NaN)
parseInt("1a", 16); //判断字符串为16进制,可选,默认为十进制
(2).转布尔型
在布尔环境中,非空字符串会被自动转换成true
(3).转成对象
会被转换成String对象。
4.空字符串的转化问题
空字符串只是在数字场合会被转换成0
在布尔场合被转换成 false
5.数值的转化问题
(1).转成字符串
在字符串中,数字可以自动转化为字符串
(2).转成对象
数值会被转换Number对象。
(3).转成布尔
只有 0 和 NaN 将被认为是false,其它值会被转换成true
6.布尔的转化问题
(1).转成字符串
会被转换成对应的字符串即"true"和"false"
(2).转成数字
true是1,而false则是0
(3).转换成对象
会被转换成Boolean对象