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型运算。!
!
!
时间: 2024-10-13 16:11:12