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]) }
学而不思则罔,思而不学则殆!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具