JavaScript 比較 和 邏輯運算符
比較運算符
運算符 ? ?說明 ? ? ? ?例子 ? ? ? ?運算結(jié)果
== ? ?等于 ? ?2 == 3 ? ?FALSE ? ?
=== ? ?恒等于(值和類型都要做比較) ? ?(2 === 2?TRUE)? ?(2 === "2" ? ?FALSE ) ??
!= ? ?不等于,也可寫作<> ? ?2 == 3 ? ?TRUE ? ?
> ? ?大于 ? ?2 > 3 ? ?FALSE ? ?
< ? ?小于 ? ?2 < 3 ? ?TRUE ? ?
>= ? ?大于等于 ? ?2 >= 3 ? ?FALSE ? ?
<= ? ?小于等于 ? ?2 <= 3 ? ?TRUE ? ?
比較運算符也可用于字符串比較。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script type="text/javascript"> var a=5,b="5"; document.write(a==b); document.write("<br />"); document.write(a===b); document.write("<br />"); document.write(a!=b); document.write("<br />"); document.write(a!==b); </script> </head> <body> </body> </html>
邏輯運算符
運算符 ? ?說明 ? ??例子 ? ??運算結(jié)果
&& ? ?邏輯與(and) ? ?x = 2; ??y = 6; ??x && y > 5 ? ?FALSE ? ?
|| ? ?邏輯或(or) ? ?x = 2; ??y = 6; ? ?x || y > 5 ? ?TRUE ? ?
! ? ?邏輯非,取邏輯的反面 ? ?x = 2; ??y = 6; ??!(x > y) ? ?TRUE ? ?
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script type="text/javascript"> var a=5,b="5"; document.write(a&&b > 10); document.write("<br />"); document.write(a||b <6); document.write("<br />"); document.write(!(a>b)); </script> </head> <body> </body> </html>
條件運算符
JavaScript 還包含了基于某些條件對變量進行賦值的條件運算符。
語法
variablename=(condition)?value1:value2?
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> 年齡:<input id="age" value="18" /> <p>是否達到上學(xué)年齡?</p> <button onclick="myFunction()">點擊按鈕</button> <p id="demo"></p> <script> function myFunction() { var age,voteable; age=document.getElementById("age").value; voteable=(age<7)?"年齡太小,繼續(xù)幼兒園":"年齡已達到,可以入學(xué)"; document.getElementById("demo").innerHTML=voteable; } </script> </body> </html>