This is the tenth day of my participation in the August Text Challenge.More challenges in August
If statement
The if statement is used to perform conditional judgments.
let a = 1;
let b = 2;
if(a > b){
console.log("A is smaller than B");
}
Copy the code
The do while statement
Do while statements do and then judge, meaning that the statement inside the loop is executed at least once
let x = "";
let i = 0;
do {
x = x +"The number is " + i + "\n"
i++;
} while (i<5);
console.log(x)
Copy the code
For statement
The for loop can be nested, such as the classic output 9 by 9 times table
let result = "";
for(let i = 1; i <10; i++){for(j = 1; j <= i; j++){ result +=` ${j} * ${i} = ${i*j} `
}
result +="\n"
}
console.log(result)
Copy the code
The for in statement
The for in statement can be used to iterate over all array elements in an array or over all attributes of an object.
let txt = "";
var content = { name: "juejin".time: 2021.huodong: "August Essay Contest" };
var x;
for (x in content) {
txt += content[x] + "";
}
console.log(txt);
Copy the code
The for of statements
The essential difference with for-in is that for-of iterates over the value of an array or object.
let arr = [2021.'juejin'."August".'Essay Call'.'the first'.10."Article"];
for (let i of arr) {
console.log(i);
}
Copy the code
Switch beyond constant-like statement
Used to select one of several code blocks, similar to if, which jumps out of the switch code block if JavaScript encounters the break keyword. This stops the execution of more code in the block as well as case testing. If a match is found and the task is completed, execution is broken randomly. No more testing required. Break saves a lot of execution time because it “ignores” the execution of other code in the Switch block. You don’t have to break the last case in the switch block. This is where the code block ends naturally.
let num = 10;
switch (true) {
case num < 0:
console.log("Less than 0.");
break;
case num >= 0 && num <= 10:
console.log("Between 0 and 10.");
break;
case num > 10 && num <= 20:
console.log("Between 10 and 20.");
break;
default:
console.log("More than 20.");
}
Copy the code
With statement
The purpose of the with statement is to set the code scope to a specific object. Use it sparingly; otherwise, performance will be affected.
var sMessage = "hello";
with(sMessage) {
alert(toUpperCase());
}
Copy the code
In this case, the with statement is used for strings, so when the toUpperCase() method is called, the interpreter checks whether it is a local function. If not, it checks the pseudo object sMessage to see if it is a method of that object. Alert then prints “HELLO” because the interpreter found the toUpperCase() method for the string “HELLO”.