javascript for循环详解
2020年5月26日小于 1 分钟约 193 字
const names = [ '张三', '李四', '王五' ]
// 常规使用for循环
for (i=0; i<names.length;i++){
console.log(names[i])
}
// 初始化多个变量
for (i=0, count=0; i<names.length;i++){
count++
}
// 省略参数
let i = 0
for ( ;i<names.length; ) {
console.log(names[i])
i++
}
// for in 循环(遍历索引)
let i;
for (i in names) {
console.log(names[i])
}
// for of 循环(遍历值)
for ( let value of names ){
console.log(value)
}
for in
循环可能不会按索引顺序遍历for of
允许遍历可迭代的数据结构:数组、字符串、映射、节点列表等- 使用
break
跳出整个循环语句,使用continue
跳过本次循环 - 非循环语句中,
break
可跳出代码块,结合条件判断使用