preface
I recently discovered JavaScript Design Patterns & Development Practices ☺ many ☺, and I am eager to share one.
The body of the
How do you write a for loop? I don’t know if most people write this.
let arr = [1.2.3]
for (let i = 0, len = arr.length; i < len; i++) {
// ...
}
Copy the code
Next show a wave of operations
let arr = [1.2.3]
for (let i = 0, val; val = arr[i++]; ) {
// ...
}
Copy the code
The first sight of her is full of curiosity, why she can normal circulation, and can be normally terminated?
I looked into the mechanics of the for loop with some questions
for(statement1; statements2; statements3) {
// The block of code being executed
}
Copy the code
Statement 1 (optional) : used to initialize variables statement 2 (optional) : conditional, continue if true, exit loop if false Statement 3 (optional) : changes the value of the initial variable, used for conditional
Val = arr[i++]; val = arr[i++]; val = arr[i++]; val = arr[i++]; val = arr[i++]
extension
😂 what value will this output be?
let arr = [1.2.0.3]
for (let i = 0, val; val = arr[i++]; ) {
// ...
}
Copy the code
Answer: outputs only 1 and 2. Reason: when I =2,ta is evaluated as false, so it exits the loop. How do you solve this situation? Write your own conditions.
let arr = [1.2.0.3]
for (let i = 0, val; ;) { val = arr[i++]if (val === undefined) {
break
} else {
// ...}}Copy the code
conclusion
How the for loop works, it smells good.
If you’re not confident about the data in your array, you should never write it this way
Looking up at the author of the book JavaScript Design Patterns and Development Practices, I still admire the author for writing such a good article and thank him for his contribution to the community.
When the for loop is used in the book, the data in the array is basically a callback function, so there is no false condition for the value of the data
Are the big guns ☺