JavaScript中的循环(6个)

Loopes

  • for
  • while
  • do while
  • for of
  • forEach
  • for in

1. for

for(initialization, condition, increment/decrement) {
  // code goes here
}

eg: 
for(let i  = 0; i < 6; i++) {
  console.log(i)
}

2. while

Using the while loop when we do not know how man iteration we go in advance.

let count = prompt('Enter a positive number: ');
white(count > 0){
  console.log(count);
  count--

3. do while

Do while run at leat once if the condition is true or false;

let count = 0;
do {
  console.log(count)
  count++
} while (count < 11)

4. for of

The for of loop is very handy to use it with array.
If we are not interested in the index of the array
a for of loop is preferable to regular for loop or forEach loop.

const numbers = [1, 2, 3, 4, 5]
for(const number of numbers) {
  console.log(number);
}

const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
for (const country of countries) {
  console.log(country.toUpperCase())
}

5. forEach

If we are interested in the index of the array
forEach is preferable to for of loop. The forEach array method takes a callback function,
the callback function takes three arguments; the item, index and the array itself.

const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
countries.forEach((country, i, arr) => {
  console.log(i, country.toUpperCase())
})

6. for in

The for in loop can be used with object literals to get the keys of the object.

const user = {
  firstName: 'ZZ',
  lastName: 'wang',
  age: 250,
  country: 'Finland',
  skills: ['HTML', 'CSS', 'JS', 'React', 'Node', 'Python', 'D3.js'],
}
for (const key in user) {
  console.log(key, user[key])
}
posted @ 2023-06-02 10:22  Felix_Openmind  阅读(20)  评论(0)    收藏  举报
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}