当前位置:网站首页>for..in和for..of的区别
for..in和for..of的区别
2022-08-05 04:25:00 【懵懵懂懂学前端】
前一段时间我碰到一个这样的问题:随便使用for..in和for..of给我带来了不可预期的后果,和我想得有点不太一样。关于for...in和for..of之间到底有什么区别?什么时候用for..in?什么时候用for..of呢?接下来,我将用代码作为示例来展示它们两者的差别。
首先看看遍历数组时 for...in和for...of的区别:


由上可知,控制台输出结果可以正常显示,对数组进行遍历时,for..in获取到的是每次遍历项的索引值,而for...of每次遍历获取到的则是每一个遍历项的value值。
在看看关于遍历对象时 for..in和for..of的区别:


通过控制台我们可以看出,使用for...in遍历对象时,每一次遍历得到的都是对象中的key值,而使用for..of遍历时则会报错(obj is not iterable),译为:obj这个对象不可迭代的,不能使用for..of遍历对象,它获取到的不是每一个遍历项的value值。
总结:
遍历数组时:for..in获取到的是每一项的索引值,而for..of获取到的是每一项的值
遍历对象时:for..in获取到的是每一项的key值(也就是属性名),而for..of不能用于遍历对象,会报错
扩展内容:Object.keys(obj)可以获取到obj的keys值,用数组形式保存;Object.values(obj)可以获取到obj的value值,也是用数组形式保存
边栏推荐
- [MRCTF2020]Ezpop(详解)
- 工业级远距离无线传输装置的功能有哪些?
- 多御安全浏览器 V10.8.3.1 版正式发布,优化多项内容
- ansible各个模块详解
- How to solve the three major problems of bank data collection, data supplementary recording and index management?
- Bosses, I noticed that a mysql CDC connector parameters scan. The incremental. Sna
- 【8.4】代码源 - 【数学】【历法】【删库】【不朴素的数列(Bonus)】
- AUTOCAD——标注关联
- UE4 通过互动(键盘按键)开门
- C++ core programming
猜你喜欢
随机推荐
七夕节赚徽章拉
Some conventional routines of program development (1)
About the installation of sklearn library
NPDP证书含金量高吗?跟PMP相比?
Please write the SparkSQL statement
Redis1: Introduction to Redis, basic features of Redis, relational database, non-relational database, database development stage
flink reads mongodb data source
Day14 jenkins部署
[Nine Lectures on Backpacks - 01 Backpack Problems]
说说数据治理中常见的20个问题
Qixi Festival earn badges
Talk about 20 common problems in data governance
1007 Climb Stairs (贪心 | C思维)
University Physics---Particle Kinematics
The log causes these pits in the thread block, you have to guard against
多御安全浏览器 V10.8.3.1 版正式发布,优化多项内容
dedecms后台生成提示读取频道信息失败的解决方法
多列属性column元素的可见性:display、visibility、opacity、垂直对齐方式:vertical-align、z-index 越大越显示在上层
DEJA_VU3D - Cesium功能集 之 058-高德地图纠偏
[informix] Resolving startup errors and solutions

![[MRCTF2020] PYWebsite](/img/d4/57e8e5ee45b742894679f3f5671516.png)






