Detailed Explanation of Operators and Flow Control Examples in Native js
- 2021-10-16 01:01:01
- OfStack
Operator
Arithmetic: + addition,-subtraction, * multiplication,/division,% modulus
Assignment: =, +=, -=, *=, /=,% =
Relationship: > , < , > =, < =, = =, = = =,! =,! = =
Logic: OR, & & And,! No
Example 1, Finding Module
window.onload = function(){
alert(0%2) //0
alert(1%2) //1
alert(2%2) //0
}
Example 2, interlaced discoloration
<body>
<ol>
<li> Modulo: It is to find the remainder </li>
<li></li>
<li></li>
</ol>
<script>
window.onload = function(){
var aLi = document.getElementsByTagName('li');
for(var i = 0; i < aLi.length; i++){
if(i % 2 == 0){
aLi[i].style.background = 'red'
}else{
aLi[i].style.background = 'green'
}
}
}
</script>
</body>
Example 3, seconds to minutes
<script>
window.onload = function () {
var a = 1568
console.log(parseInt(a / 60) + ' Points ' + a % 60 + ' Seconds ')
}
</script>
Example 4, +=
a = a + 1;
a+=1
a++
Program flow control
switch
<script>
window.onload = function () {
var name = 'abc';
var sex = ''
switch (sex) {
case ' Male ':
alert(name + ' How do you do, sir ');
break;
case ' Female ':
alert(name + ' How do you do, ma'am ');
break;
default:
alert(name + ' How do you do ')
}
}
</script>
break, continue
window.onload = function(){
for(var i = 0; i < 5; i++){
if(i == 3){
//break; // The whole loop is interrupted
continue; // This loop is interrupted
}
alert(i)
}
}
What is true and what is false
window.onload = function(){
// True: true , not 0 Numeric value, non-empty string ('false' Or ' ') , non-null object
// Fake : false , numerical value 0 Empty string, empty object (null) , undefined
var a = 'false'
if(a){
alert(' Really ')
}else{
alert(' False ')
}
}