js类型测试学习
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <title> JS类型 测试 并验证</title> </head> <body><form method="post" action=""><input type="text" name="username" value="" id="username"></form> </body></html> <script type="text/javascript"> <!--var time1 = 0;if(time1 == "") {alert("true"); } /** * 当表单中没有username2时,得到的值 为null * 当存在username2时,得到的值为"" 或者 为表单中的value属性的值 */var time2 = document.getElementById("username2");if(time2 == null) {alert("true"); } // 且记,此处undefined必须用引用括起来,因为函数返回类型是字符串类型的if(typeof(IsTime)=="undefined"){ alert("判断类型是否被定义,未被定义!"); } if(typeof(IsTime) == undefined ){ alert("判断类型是否被定义,未被定义!"); } /** * == 在JS中是比较值 * === 在JS中不光比较值,还比较类型 */alert("123"==123); // alert truealert("0123" == 0123); // alert falsealert("123" === 123); // alert false/** *undefined , null , "" , 0 这四个值转换为逻辑值时是false. *其他所有东西转换逻辑值都是true, * 下面四个方法都 alert true */if("") {} else {alert(""" == false");}if(0) {} else {alert("0 == false");}if(null) {} else {alert("null == false");}if(undefined){} else {alert("undefined == false");} //--> </script>
?
总结: js是弱类型语言,使用方便的同时,对细节的要求更加严格,使用时要小心谨慎!