11-14强制类型转换
强制类型转换String
<!DOCTYPE html>
<html lang="zh-CH"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><script>// 将其他类型转换为String类型// 方法一:调用被转换数据类型的toString方法,null和undefined不行var a = 123;var b = a.toString();document.write(typeof b);document.write(b);//方法二:调用String函数c = String(a);document.write(typeof c);document.write(c);var d = null;e = String(d);document.write(typeof e);document.write(e);</script>
</body></html>
强制类型转换Number
<!DOCTYPE html>
<html lang="zh-CH"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><script>// 将其他类型转换为Number类型//方法一:调用Number函数a = 123;b = Number(a);document.write(typeof b);document.write(b);//有非数字,则转换成NaNc = "123abc";d = Number(c)document.write(typeof d);document.write(d);//为空值或一个空格,转换成0var e = null;f = Number(e);document.write(typeof f);document.write(f);//为布尔型,转为数字,0,1var g = true;h = Number(g);document.write(typeof h);document.write(h);//调用parseint()函数将a转换为Number,读到非数字结束j=parseInt(g);document.write(typeof j);document.write(j);</script>
</body></html>
其他进制的数字
<!DOCTYPE html>
<html lang="zh-CH"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><script>//其他进制的数字a = 123;//16进制a=0x10;//8进制a=070;document.write(a);</script>
</body></html>
转换为Boolean
<!DOCTYPE html>
<html lang="zh-CH"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><script>//将其他类型转换为Booleanvar a=123;//调用Boolean()函数a=Boolean(a);//除了0和NaN,其余都是truedocument.write(typeof a);document.write(a);b=true;c=Boolean(b);document.write(typeof c);document.write(c);e=NaN;f=Boolean(e);document.write(typeof f);document.write(f);</script>
</body></html>
