1.类型转换
parseInt :将字符串转换为整数,只能转换成整数;
parse Float :可以将字符串转换为小数;
应用:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
window.onload=function(){
oTxt1=document.getElementById("text1");// 2
oTxt2=document.getElementById("text2");// 3
oBtn1=document.getElementById("button1");
oBtn1.onclick=function(){
alert(oTxt1.value+oTxt2.value); // 23
alert(parseInt(oTxt1.value)+parseInt(oTxt2.value)); // 5
};
alert(parseInt('2.14'));// 2
alert(parseFloat('2.14')); // 2.14
};
</script>
</head>
<body>
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="button" id="button1" value="结果" />
</body>
</html>
如果text里面输入的是字符串,将 报NAN(Not A Number)错误!
这对于使用者来说并不知道出现了什么错误,所以应该判断他们相应的提示。每一个输入框的NAN错误都不一样。
判断是否有NAN错误用 isNaN();
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
window.onload=function(){
oTxt1=document.getElementById("text1");
oTxt2=document.getElementById("text2");
oBtn1=document.getElementById("button1");
oBtn1.onclick=function(){
var n1=parseInt(oTxt1.value);
var n2=parseInt(oTxt2.value);
if(isNaN(n1)){
alert('第一个数输入错误!');}
else if(isNaN(n2)){
alert('第二个数输入错误!');}
else{alert(n1+n2); }// 5
};
};
</script>
</head>
<body>
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="button" id="button1" value="结果" />
</body>
</html>
2.隐式类型转换
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
function fnA(){
var a=2;
var b='3';
alert(a+b);// 23 ‘+’: 1,字符串连接 2,数字相加 电脑比较懒,能一次计算的不进行转换;
alert(b-a);// 1 ‘-’ 1.字符串相减 只进行这一步计算,所以必须转换相同类型;
var b='6';
var c=6;
alert(b==c); //true 先转换相同类型在比较
alert(b===c); //false 不转换直接比较
}
fnA();
</script>
</head>
<body>
</body>
</html>
3.js命名前缀
4.闭包
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
function fnA(){
var a=2;
var b='3';
function fnB(){
alert(a);
}//子函数可以使用父函数中的变量
fnB();
}
fnA();
</script>
</head>
<body>
</body>
</html>