JS—应用中的一些小问题

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值