for…in 循环:只能获得对象的键名,不能获得键值 for…in 循环主要是为了遍历对象而生,不适用于遍历数组 for…of 循环:允许遍历获得键值 for…of 循环可以用来遍历数组、类数组对象,字符串、Set、Map 以及 Generator 对象
//对于普通对象,没有部署原生的 iterator 接口,直接使用 for...of 会报错
var obj = {
'name': 'lin',
'age': 12
}
for(let key of obj) {
console.log('for of obj', key) // VM1263:6 Uncaught TypeError: obj is not iterable
at <anonymous>:6:17
}
//for...in 循环不仅遍历数字键名,还会遍历手动添加的其它键,甚至包括原型链上的键。for...of 则不会这样
let arr = [1, 2, 3,]
arr.set = 'hello world' // 手动添加的键
Array.prototype.name = 'hello hi' // 原型链上的键
for(let item in arr) {
console.log('item', item)
}
//item 0
// item 1
// item 2
// item set
// item name
for(let value of arr) {
console.log('value', value)
}
//item 0
// item 1
// item 2
//forEach 循环无法中途跳出,break 命令或 return 命令都不能奏效
arr.forEach(item => {
if(item % 2 === 0) {
break
}
console.log('item', item)
})
//Uncaught SyntaxError: Illegal break statement at Array.forEach (<anonymous>at <anonymous>:1:5
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有