当前位置: 首页> 文旅> 艺术 > for of 和 for in 的区别

for of 和 for in 的区别

时间:2025/7/11 7:36:55来源:https://blog.csdn.net/weixin_72324200/article/details/139535871 浏览次数:0次

for in适合遍历对象, for of适合遍历数组。 for in遍历的是数组的索引,对象的属性,以及原型链上的属性。

1.循环数组

区别一:for in 和 for of 都可以循环数组。for in 输出的是数组的index下标,而for of 输出的是数组的每一项的值。

const arr = [1,2,3,4]// for ... in
for (const key in arr){console.log(key) // 输出 0,1,2,3}// for ... of
for (const key of arr){console.log(key) // 输出 1,2,3,4}

2.循环对象

区别二:for in 可以遍历对象,for of 不能,只能遍历带有iterator接口的,例如Set,Map,String,Array

const object = { name: 'lx', age: 23 }// for ... infor (const key in object) {console.log(key) // 输出 name,ageconsole.log(object[key]) // 输出 lx,23}// for ... offor (const key of object) {console.log(key) // 报错 Uncaught TypeError: object is not iterable}

3.数组对象

const list = [{ name: 'lx' }, { age: 23 }]for (const val of list) {console.log(val) // 输出{ name: 'lx' }, { age: 23 }for (const key in val) {console.log(val[key]) // 输出 lx,23}}
​

参考网址:for in 和 for of的区别_for in for of区别-CSDN博客

关键字:for of 和 for in 的区别

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: