当前位置:网站首页>JS中是如何使用for..of来遍历对象
JS中是如何使用for..of来遍历对象
2022-07-27 05:03:00 【weixin_46051260】
for…of是允许遍历一个含有iterator接口的数据结构(数组) 并且返回各项的值
1)需要遍历的是类数组对象,使用数组的Array.from转为数组
var obj={
0:1,
1:2,
2:3,
length:3
}
obj=Array.from(obj)
for(let value of obj){
console.log(value);//1 2 3
}
2)需要遍历的对象不是对象,给对象添加一个Symbol.iterator属性(默认的iterator接口),指向迭代器
iterator遍历过程:
- 创建一个指针对象,指向当前数据结构的起始位置
- 第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员
- 第二次调用指针对象的next方法,指针就指向数据结构的第二个成员
- 不断的调用指针对象的next方法,直到它指向数据结构的结束位置
每一次调用next方法,都会返回数据结构当前的成员信息,返回一个包含value和done两个属性的对象
- value:当前成员的值
- done:是一个布尔值,表示遍历是否结束
var Person={
name:'jack',
age:18,
height:185,
weight:160,
sex:'男'
}
Person[Symbol.iterator]=function(){
var key=Object.keys(this)
var index=0
return{
next() {
if (index < key.length) {
return {
value: [key[index++]], done: false }
} else {
return {
value: undefined, done: true }
}
}
}
}
for (item of Person) {
console.log(item);
}
边栏推荐
猜你喜欢
随机推荐
【C语言switch分支语句和循环语句】
C WPF uses listbox to implement ruler control
Redis transaction
后台实现sku 管理
node 安装调试
Trying to evolve_ My first CSDN blog
Differences among bio, NiO and AIO
Cenos7更新MariaDB
Share a multiple-choice question about define (including the replacement rules, program environment and preprocessing related knowledge of define during precompiling)
流程控制-分支
268.missing number of leetcode
下载url-loader,用limit指定图片大小后,显示不出图片
Makefile is easy to understand and explain
pytorch安装新坑
Hi3516dv300 environment setup
JS中apply、call、bind的区别
块,行内块元素之间存在间隙
Li Hongyi machine learning team learning punch in activity day04 - Introduction to deep learning and back propagation mechanism
Program environment and preprocessing (Part 2): define, undef, command line compilation, conditional compilation, file inclusion (super full collation, recommended collection!!!
后台用户管理展示添加功能实现








