当前位置:网站首页>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值,也是用数组形式保存
边栏推荐
- iMedicalLIS listener (2)
- bytebuffer use demo
- Day14 jenkins deployment
- 【8.1】代码源 - 【第二大数字和】【石子游戏 III】【平衡二叉树】
- UE4 第一人称角色模板 添加蹲伏功能
- There are several common event handling methods in Swing?How to listen for events?
- Redis key basic commands
- 1007 Climb Stairs (greedy | C thinking)
- [MRCTF2020] Ezpop (detailed)
- Application status of digital twin technology in power system
猜你喜欢

UE4 opens door via interaction (keyboard key)

狗仔队:表面编辑多视点图像处理

Day019 方法重写与相关类的介绍

In the hot summer, teach you to use Xiaomi smart home accessories + Raspberry Pi 4 to connect to Apple HomeKit

8.04 Day35-----MVC three-tier architecture
![[MRCTF2020]PYWebsite](/img/d4/57e8e5ee45b742894679f3f5671516.png)
[MRCTF2020]PYWebsite

Four-digit display header design

动力小帆船制作方法简单,电动小帆船制作方法

how to measure distance from point to face in creo
![[CISCN2019 South China Division]Web11](/img/15/843334fec0a5cc8cfaba92aab938db.png)
[CISCN2019 South China Division]Web11
随机推荐
Index Mysql in order to optimize paper 02 】 【 10 kinds of circumstances and the principle of failure
dedecms dream weaving tag tag does not support capital letters fix
[informix] Resolving startup errors and solutions
Redis1: Introduction to Redis, basic features of Redis, relational database, non-relational database, database development stage
App快速开发建设心得:小程序+自定义插件的重要性
AUTOCAD - dimension association
token, jwt, oauth2, session parsing
Four-digit display header design
UE4 更改组件变量 (以修改第一人称角色模板的最大行走速度和跳跃高度为例)
DEJA_VU3D - Cesium功能集 之 059-腾讯地图纠偏
[MRCTF2020] Ezpop (detailed)
Spark Basics [Introduction, Getting Started with WordCount Cases]
多御安全浏览器 V10.8.3.1 版正式发布,优化多项内容
flink读取mongodb数据源
UE4 在游戏运行时更改变量 (通过鼠标滑轮来更改第一人称角色的最大行走速度)
Mysql的undo log详解
Haproxy搭建Web群集
36-Jenkins-Job Migration
upload上传图片到腾讯云,如何上传图片
[BSidesCF 2019]Kookie