JavaScript is a scripting language often used in web development and other applications. There are many kinds of loops in JS that are used to repeatedly execute a piece of code. This article will introduce loops in JavaScript in detail.
In JavaScript, the following types of commonly used loops are:
for (initialization; condition; increment) { // code to be executed }
Among them,initialization
is the starting value of the loop, which can be a variable or a constant;condition
is the loop condition, When the condition is false, the loop ends;increment
is the change value after each execution of the loop, similar to self-increment or self-decrement. The sample code is as follows:
for (let i = 0; i < 10; i++) { console.log(i); }
The while loop is another iterative control structure that executes a block of code over and over again as long as a condition is true. Its syntax is as follows:
while (condition) { // code to be executed }
The sample code is as follows:
let i = 0; while (i < 10) { console.log(i); i++; }
The do-while loop is similar to the while loop, but different The difference is that the conditional check is executed after the code block has been executed. Even if the condition is false initially, it will be executed at least once. Its syntax is as follows:
do { // code to be executed } while (condition);
The sample code is as follows:
let i = 0; do { console.log(i); i++; } while (i < 10);
for-in loop is used to traverse objects or arrays attributes or elements. Its syntax is as follows:
for (variable in object) { // code to be executed }
Among them,variable
is the name of the variable to be iterated, andobject
is the object to be iterated. The sample code is as follows:
const myObj = { a: 1, b: 2, c: 3 }; for (const property in myObj) { console.log(property + ": " + myObj[property]); }
for-of loop is used to traverse iterable objects, such as arrays and strings. Its syntax is as follows:
for (variable of iterable) { // code to be executed }
Among them,variable
is the variable name to be iterated, anditerable
is the object to be iterated. The sample code is as follows:
const myArray = [1, 2, 3]; for (const element of myArray) { console.log(element); }
The above are the commonly used loops in JavaScript. Each loop has its own applicable scenarios. When writing JavaScript code, you need to choose different loop structures according to different needs. I hope this article is helpful for everyone to understand JavaScript loops.
The above is the detailed content of How many types of loops are there in javascript?. For more information, please follow other related articles on the PHP Chinese website!