js面試題--------JS中數字和字符,布爾類型相加相減問題


JS中數字和字符相加相減問題

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>

</head>
<body>
</body>
</html>
<script type="text/javascript">
    var a = 100;
    var b = "100";
    alert(b- a);
    alert(typeof (b- a));
    alert(a + b - a);
    alert(typeof (a + b - a));
    alert(a + b);
    alert(typeof (a + b));
    alert(a + b - b);
    alert(typeof (a + b - b));
    alert(a + b - b - b);
    alert(typeof (a + b - b - b));
    alert(true + 1);//2 ,true被轉化為1,false轉化為0
    alert(true + "1");//true1 ,  true被轉化為字符串“true”
</script>

  執行結果   

  0

 number

 100000

 number

 100100

 string

 100000

 number

 99900

 number

2

true1

 

由此可知道JS在進行這種運算時 僅僅會在2個值相加時優先推斷為string類型 其它情況下(比如“-”。“*”。“/”)都默覺得number型運算。!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM