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 @   Felix_Openmind  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}
点击右上角即可分享
微信分享提示