js数据强转
2020-03-31 22:06 默默不语 阅读(207) 评论(0) 编辑 收藏 举报<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript"> /* 强转 */ /* 1.其他类型转为Number类型 */ var s1 = "10"; var s2 = "abc"; var b1 = false; var o1 = Object(10); var o2 = new Array(); o2[0]=1; o2[1]=2; var o3 = null; document.write("String转number,可转:"+Number(s1)+"<br>");//10 document.write("String转number,不可转:"+Number(s2)+"<br>");//Nan document.write("boolean转number,可转:"+Number(b1)+"<br>");//0 document.write("Object转number=:"+Number(o2)+"<br>");//若o2中只有o2[0],则为1,若还有o2[1],则为NaN document.write("null转number:"+Number(o3)+"<br>");//0 /* 能转就转,不能转就为NaN, */ /* 2.其他类型转为boolean类型 */ var nb = 10; var sb = "abc"; var ob = new Object(1); var unb; //2.1Number转Boolean document.write("Number转Boolean:"+Boolean(nb)+"<br>");//非零转成true,0转成false //2.2String转Boolean document.write("String转Boolean:"+Boolean(sb)+"<br>");//非空转成true,空转成false //2.3Object转Boolean document.write("Object转Boolean:"+Boolean(ob)+"<br>");//非null转成true,null转成false //2.4声明未赋值(undefined)转Boolean document.write("声明未赋值(undefined)转Boolean:"+Boolean(unb)+"<br>");//false
</script> </head> <body> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript"> /* 3.boolean转String */ var b = true; document.write("Boolean转String:"+typeof(b.toString())+"<br>");//String /* 4.String转Number */ var s = "10"; document.write("String转Number:"+typeof(parseInt(s) )+"<br>");//number </script> </head> <body> </body> </html>