当前位置:网站首页>Difference between for..in and for..of
Difference between for..in and for..of
2022-08-05 05:11:00 【Ability to learn the front-end】
Some time ago I encountered such a problem: using for..in and for..of casually brought me unpredictable consequences, which were a little different from what I thought.What exactly is the difference between for...in and for..of?When to use for..in?When to use for..of?Next, I will use code as an example to show the difference between the two.
First look at the difference between for...in and for...of when traversing an array:
As can be seen from the above, the console output results can be displayed normally. When traversing the array, for..in obtains the index value of each traversal item, while for...of obtains the index value of each traversal item.is the value of each traversal item.
Look at the difference between for..in and for..of when iterating over objects:
Through the console, we can see that when using for...in to traverse an object, each traversal will get the key value in the object, but when using for..of traversal, an error will be reported (obj is not iterable), translated as: the obj object is not iterable and cannot be used to traverse the object using for..of, it does not get the value of each traversal item.
Summary:
When traversing the array: for..in gets the index value of each item, and for..of gets the value of each item
When traversing objects: for..in gets the key value of each item (that is, the attribute name), while for..ofcannotFor traversing objects, an error will be reported
Extended content: Object.keys(obj) can get the keys value of obj and save it in the form of an array; Object.values(obj) can get the value of obj and save it in the form of an array
边栏推荐
猜你喜欢
Day019 Method overriding and introduction of related classes
Dephi reverse tool Dede exports function name MAP and imports it into IDA
【cesium】元素高亮显示
Structured light 3D reconstruction (1) Striped structured light 3D reconstruction
8.04 Day35-----MVC三层架构
[Student Graduation Project] Design and Implementation of the Website Based on the Web Student Information Management System (13 pages)
Excel Paint
【学习笔记之菜Dog学C】动态内存管理之经典笔试题
Detailed explanation of each module of ansible
App快速开发建设心得:小程序+自定义插件的重要性
随机推荐
The role of DataContext in WPF
Qt produces 18 frames of Cupid to express his love, is it your Cupid!!!
Flutter学习5-集成-打包-发布
Develop your own node package
Excel画图
人性的弱点
Detailed explanation of each module of ansible
MySQL Foundation (1) - Basic Cognition and Operation
University Physics---Particle Kinematics
Redis哨兵模式配置文件详解
Judgment statement _switch and case
The solution to the failure to read channel information when dedecms generates a message in the background
【学习笔记之菜Dog学C】动态内存管理之经典笔试题
浅析主流跨端技术方案
Understanding and use of C# on set() and get() methods
JeeSite New Report
MySQL中控制导出文件后变为了\N有什么解决方案吗?
判断语句_switch与case
Using QR codes to solve fixed asset management challenges
数字孪生技术在电力系统中的应用现状