ES5
forEach缺陷:
不能用break语句跳出循环且不能在这个封闭的函数内使用return语句。
for in // 比较适用在对象上面的一个循环遍历,但是数组也可以用
var arry = [1, 2, 3, 4, 5]
for (index in arry) {
console.log(index) // 0,1,2,3,4
if (index === 3) {
break; // 不可以被打断
}
console.log(arry[index]) // 1,2,3,4,5
console.log(typeof index) // string
}
ES6
for of // 支持集合 ---试了一下chrome,现在是支持的
for (index of arry) {
console.log(index) // 0,1,2,3,4
if (index === 3) {
break; // 可以被打断
}
console.log(arry[index]) // 1,2,3,4,5
console.log(typeof index) // number
}
时间: 2025-01-01 19:51:47