1. 程式人生 > >2-JS運算符

2-JS運算符

字符串拼接 als 類型 quotient 字符 round rod ack 運算

1、運算符

1)算術運算符

 1 <button id="btn" onclick="suanShu()">運算</button>
 2 <script>
 3     // + - * / % ++ --
 4     var i = 521,j = 1314;
 5     var sum = i + j;
 6     var difference = j - i;
 7     var product = i * j;
 8     var quotient = j / i;
 9     var congruent = j % i;  //j除以i後的余數
10
var addSelf = i++; // ++在前,先+後運算,++在後,先運算後加 此時i= 522 11 var selfCut = --j; // --在前,先+後運算,--在後,先運算後加 此時j=1313 12 function suanShu() { 13 document.getElementById("sumId").innerHTML = "兩數相加結果:" + sum; 14 document.getElementById("differenceId").innerHTML = "兩數相減結果:" + difference;
15 document.getElementById("productId").innerHTML = "兩數相乘結果:" + product; 16 document.getElementById("quotientId").innerHTML = "兩數相除結果:" + quotient; 17 document.getElementById("congruentId").innerHTML = "兩數取余結果:" + congruent; 18 document.getElementById("addSelfId").innerHTML
= "i自加結果:" + addSelf; 19 document.getElementById("selfCutId").innerHTML = "j自減結果:" + selfCut; 20 } 21 </script> 22 <p id="sumId"></p> 23 <p id="differenceId"></p> 24 <p id="productId"></p> 25 <p id="quotientId"></p> 26 <p id="congruentId"></p> 27 <p id="addSelfId"></p> 28 <p id="selfCutId"></p>

2)賦值運算符

1 // = += -+ *= /= %=
2     var x = i+=j;       //i = i+j
3     var y = i -=j;      //i = i-j
4     var m = i *= j;     //i = i*j
5     var n = i /= j;      //i = i/j

3)字符串操作

字符串拼接:var i= 5+"5",結果為55.任何數據類型與字符串數據類型相加,都會轉換為 字符串類型做處理

4)比較運算符 (== 、=== 、 != 、!==、>、<、>=、<= )

 1 <script>
 2     var m = 12,n = "12";
 3     var x = 23,y = "23";
 4     document.write(m==n);   //true
 5     document.write(m===n);  //false
 6     document.write(m!=x);   //true
 7     document.write(m!==n);  //true
 8     document.write(m>y);    //false
 9     document.write(x<=n)    //false
10 </script>

5)邏輯運算符(&&、||、!)

1 <script>
2     var i = 100,j = 200;
3     document.write(i>100 && j<=200);    //與,兩者都需滿足
4     document.write(i>100 || j<=200);    //或,兩者滿足其一
5     document.write(!(i==j));    // 取反
6 </script>

6)條件運算符

<script>
    var i = 11;
    document.write(i>10 ? "i大於10":"i小於10"); //條件為真執行前,為假執行後
</script>

2-JS運算符