当前位置:网站首页>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,比较好理解;
边栏推荐
- Is container technology really the savior of environmental management?
- BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection Paper Notes
- 【微波工程学习记录1】功率分配器和定向耦合器
- 最新国产电源厂家及具体型号pin-to-pin替代手册发布
- How to check if the online query suddenly slows down
- 颠覆性创新招商,链动2+1是个怎么样的制度模式?
- C#使用计时器
- 生信实验记录(part2)--tf.reduce_sum()用法介绍
- Mysql数据库安装配置详细教程
- ABP中的数据过滤器
猜你喜欢
Some Experiences of Embedded Software Logging
postgresql参数意义
如何防止离职员工把企业文件拷贝带走?法律+技术,4步走
【iframe父页面调用子页面的方法】踩坑:获取元素的时候需要用 `[x]`是关键,不能用`.eq(x)`否则获取不到。
划分字母区间[贪心->空间换时间->数组hash优化]
双机热备综合实验(VRRP+OSPF+VTP+NAT+DHCP+PVSTP+单臂路由)
MySQL advanced query
MySQL indexes and transactions
编程技巧│selenium 更新 chromedriver 驱动
MSTP - Multiple Spanning Tree (Case + Configuration)
随机推荐
postgresql parameter meaning
How to determine the size of the version number
SAP ABAP JSON 格式数据处理
C # - delegate detailed usage
#yyds Dry Goods Inventory#[Yugong Series] August 2022 Go Teaching Course 008-Integer of Data Types
Vim take on a window.
安装dlib库
请讲一讲JS中的 for...in 与 for...of (下)
异常:try catch finally throws throw
ABP中的数据过滤器
Shell 文本三剑客 Sed
More parameter exposure of Pico 4: Pancake + color perspective, and Pro version
sql 使用到where和groupby时到底怎么建立索引?
SystemVerilog: 验证知识点点滴滴
划分字母区间[贪心->空间换时间->数组hash优化]
研发项目流程规范
Use mysql statement to operate data table (table)
Engineering Design of Single-sided PCB Routing Impedance
软件测试面试题:什么是数据的对立性,有几个层次?
【服务器数据恢复】raid5崩溃导致lvm信息和VXFS文件系统损坏的数据恢复案例