当前位置:网站首页>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值,也是用数组形式保存
边栏推荐
猜你喜欢

There are a lot of 4T hard drives remaining, prompting "No space left on device" insufficient disk space

write the story about us

从企业的视角来看,数据中台到底意味着什么?

bytebuffer use demo
![[MRCTF2020]PYWebsite](/img/d4/57e8e5ee45b742894679f3f5671516.png)
[MRCTF2020]PYWebsite
![[BJDCTF2020] EasySearch](/img/60/464de3bcdda876171b9f61ad31bff1.png)
[BJDCTF2020] EasySearch
![[MRCTF2020]Ezpop(详解)](/img/19/920877ca36d1eda8d118637388ab05.png)
[MRCTF2020]Ezpop(详解)

Use IDEA to connect to TDengine server

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

bytebuffer 内部结构
随机推荐
Analyses the mainstream across technology solutions
mutillidae下载及安装
Cron(Crontab)--use/tutorial/example
【树莓派】树莓派调光
Learning and finishing of probability theory 8: Geometric and hypergeometric distributions
University Physics---Particle Kinematics
[SWPU2019]Web1
[Nine Lectures on Backpacks - 01 Backpack Problems]
Homework 8.4 Interprocess Communication Pipes and Signals
pyqt5 + socket 实现客户端A经socket服务器中转后主动向客户端B发送文件
Index Mysql in order to optimize paper 02 】 【 10 kinds of circumstances and the principle of failure
bytebuffer use demo
SkiaSharp 之 WPF 自绘 粒子花园(案例版)
[informix] Resolving startup errors and solutions
The first performance test practice, there are "100 million" a little nervous
[Surveying] Quick Summary - Excerpt from Gaoshu Gang
DEJA_VU3D - Cesium功能集 之 059-腾讯地图纠偏
[BSidesCF 2019] Kookie
小程序_动态设置tabBar主题皮肤
iMedicalLIS listener (2)