如何在 JavaScript 中构建循环? [英] How do I build a loop in JavaScript?

查看:24
本文介绍了如何在 JavaScript 中构建循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 JavaScript 中构建循环?

How can I build a loop in JavaScript?

推荐答案

For 循环

for (i = startValue; i <= endValue; i++) {
    // Before the loop: i is set to startValue
    // After each iteration of the loop: i++ is executed
    // The loop continues as long as i <= endValue is true
}

For...in 循环

for (i in things) {
    // If things is an array, i will usually contain the array keys *not advised*
    // If things is an object, i will contain the member names
    // Either way, access values using: things[i]
}

使用 for...in 循环遍历数组是不好的做法.它违反了 ECMA 262 标准,并且可能会导致问题- 将标准属性或方法添加到 Array 对象,例如通过 原型.(感谢 Chase Seibert 在评论中指出这一点)

It is bad practice to use for...in loops to itterate over arrays. It goes against the ECMA 262 standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by Prototype. (Thanks to Chase Seibert for pointing this out in the comments)

While 循环

while (myCondition) {
    // The loop will continue until myCondition is false
}

这篇关于如何在 JavaScript 中构建循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆