当前位置:网站首页>Please talk about for...in and for...of in JS (below)
Please talk about for...in and for...of in JS (below)
2022-08-11 01:41:00 【lovetomato1106】
start
- Learn from the previous article for…in;
- Learn this article for…of ;
- And sum up the difference between the two;
起因
As the so-called day and night have dreams,often dreamfor...of.
The reason is that I read Teacher Ruan Yifeng before《ECMAScript 6 入门》,At the time, I saw such a piece of content as shown below:ECMAScript 6 入门-18.Iterator 和 for…of 循环 原文链接
It was not fully understood at first,今天再来学习一下.

初步认识
先看看MDN的解释
MDN 的解释:
for…of 语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
思考:
可迭代对象
什么是可迭代对象? Here are some examples可迭代对象(Array,Map,Set,String,TypedArray,arguments 对象等)
MDN 中是这样说:要成为可迭代对象, 一个对象必须实现 @@iterator 方法.这意味着对象(或者它原型链上的某个对象)必须有一个键为 @@iterator 的属性,可通过常量 Symbol.iterator 访问该属性;
《ECMAScript 6 入门》中是这样说:一个数据结构只要部署了 Symbol.iterator 属性,就被视为具有 iterator 接口,就可以用 for…of 循环遍历它的成员.
打印一下 MDN those iterable objects enumerated,See if it's accurate.(For the time being, let's take an array as an example)
验证
这里我偷个懒,直接打印 Symbol.iterator 属性.
// Array
var arr = [1, 2]
console.log(arr[Symbol.iterator])
// Map
var m = new Map()
console.log(m[Symbol.iterator])
// Set
var set = new Set()
console.log(set[Symbol.iterator])
// String
var str = '你好'
console.log(str[Symbol.iterator])
// TypedArray
var typeArr = new Uint8Array([0x00, 0xff])
console.log(typeArr[Symbol.iterator])
// arguments
;(function () {
console.log(arguments[Symbol.iterator])
})(1, 2, 3)
/* [Function: values] [Function: entries] [Function: values] [Function: [Symbol.iterator]] [Function: values] [Function: values] */
Symbol.iterator 属性
for…of The whole logic is with the help of propertiesSymbol.iterator指向的函数.
This function returns an object when executed;
返回的对象有 next 方法,Each execution returns an object;
例如{value: 10, done: false}
演示一下:
var arr = [1, 2, 3, 4]
let fn = arr[Symbol.iterator]()
console.log(fn.next())
console.log(fn.next())
console.log(fn.next())
console.log(fn.next())
console.log(fn.next())
console.log(fn.next())
/* { value: 1, done: false } { value: 2, done: false } { value: 3, done: false } { value: 4, done: false } { value: undefined, done: true } { value: undefined, done: true } */
为了更好理解:I rewrite the array here Symbol.iterator 属性
var arr = [1, 2, 3, 4, 5]
arr[Symbol.iterator] = function () {
const self = this
let index = 0
return {
next() {
if (index < self.length) {
return {
value: self[index++] + 'Additional processing of the traversed data',
done: false,
}
}
return {
value: undefined, done: true }
},
}
}
console.log(arr) // [ 1, 2, 3, 4, 5, [Symbol(Symbol.iterator)]: [Function] ]
for (const i of arr) {
console.log(i)
}
/* 1Additional processing of the traversed data 2Additional processing of the traversed data 3Additional processing of the traversed data 4Additional processing of the traversed data 5Additional processing of the traversed data */
Why does an object have no properties Symbol.iterator
for…of An error will be reported when traversing the object:Uncaught TypeError: obj is not iterable
原因:
摘抄自 《ECMAScript 6 入门》
对象(Object)之所以没有默认部署 Iterator 接口,是因为对象的哪个属性先遍历,哪个属性后遍历是不确定的,需要开发者手动指定.本质上,遍历器是一种线性处理,对于任何非线性的数据结构,部署遍历器接口,就等于部署一种线性转换.不过,严格地说,对象部署遍历器接口并不是很必要,因为这时对象实际上被当作 Map 结构使用,ES5 没有 Map 结构,而 ES6 原生提供了.
调用 Iterator 接口的场合
- 数组和 Set 的解构赋值
- 扩展运算符
- for…of
- Array.from()
- Map(), Set(), WeakMap(), WeakSet()(比如 new Map([[‘a’,1],[‘b’,2]]))
- Promise.all()
- Promise.race()
for…of 与 for…in 的区别
无论是 for…in 还是 for…of 语句都是迭代一些东西.它们之间的主要区别在于它们的迭代方式.
for…in 语句以任意顺序迭代对象的可枚举属性.
for…of 语句遍历可迭代对象定义要迭代的数据.
There is one more difference mentioned here,for…in 是 ES3 实现的,而 for…of 是 ES6 实现的,所以 for…of There is a high probability that it will be used when used in a production environment babel 转换.
end
- 写到这里,There is a preliminary understanding of these two methods;
- In fact, there is no need to say rote memorization:for…in what can be traversed,for…of Can't traverse anything.Know how iteration works,比较好理解;
边栏推荐
- MySQL indexes and transactions
- 生信实验记录(part2)--tf.reduce_sum()用法介绍
- postgresql parameter meaning
- vim simple save window id
- 深度解析:什么是太爱速M抢单模式?
- Experiment record of Shengxin (part3)--scipy.spatial.distance_matrix
- 【服务器数据恢复】raid5崩溃导致lvm信息和VXFS文件系统损坏的数据恢复案例
- 数据库数据采集利器FlinkCDC
- paddle2.3和torch1.8在SentenceBert上的性能对比
- Single-chip human-computer interaction--matrix key
猜你喜欢
随机推荐
21、阿里云oss
QT+VTK+PCL拟合圆柱并计算起始点、中止点
SAP ABAP JSON 格式数据处理
Construction inspection, no rules and no square
划分字母区间[贪心->空间换时间->数组hash优化]
Sub-database sub-table ShardingSphere-JDBC notes arrangement
Flink二阶段提交
Deep Learning【第二章】
微服务概念
进程间通信(IPC)的分类以及通信方式的发展
络达开发---UI定义+自定义按钮事件
22. Inventory service
简陋的nuxt3学习笔记
vim取上个窗口号.
安装dlib库
本周四晚19:00知识赋能第六期第5课丨OpenHarmony WiFi子系统
异常:try catch finally throws throw
ABP中的数据过滤器
【视频】报告分享|2021年保险行业数字化洞察
BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection 论文笔记










