当前位置:网站首页>How to use for..Of to traverse objects in JS
How to use for..Of to traverse objects in JS
2022-07-27 05:41:00 【weixin_ forty-six million fifty-one thousand two hundred and si】
for…of Is to allow traversal of a iterator Data structure of the interface ( Array ) And return the value of each item
1) What needs to be traversed is the class array object , array-based Array.from Converted to an array
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) The object to be traversed is not an object , Add one to the object Symbol.iterator attribute ( default iterator Interface ), Point to the iterator
iterator Ergodic process :
- Create a pointer object , Point to the start of the current data structure
- The first call to the next Method , You can point a pointer to the first member of a data structure
- The second call to the next Method , Pointer to the second member of the data structure
- Constantly calling the pointer object next Method , Until it points to the end of the data structure
Every time you call next Method , Will return the current member information of the data structure , Returns a containing value and done Objects with two properties
- value: The value of the current member
- done: It's a Boolean value , Indicates whether the traversal ends
var Person={
name:'jack',
age:18,
height:185,
weight:160,
sex:' male '
}
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);
}
边栏推荐
- Maintain login and route jump
- [MRCTF2020]Ezpop 1
- 分享力扣—189.轮转数组 的三种解法
- Logic of image uploading
- Asynchronous data SMS verification code
- Program environment and preprocessing (Part 1): how does a program run successfully?
- First knowledge of C language -- what is C language
- Pytorch installation new pit
- 函数和箭头函数
- 下载url-loader,用limit指定图片大小后,显示不出图片
猜你喜欢
随机推荐
Js中如何进行隐式转换
SSTI 模板注入
一本通1201——斐波那契数列
一本通顺序结构程序设计题解(第一章)
云E办项目之部门管理
[NPUCTF2020]ReadlezPHP 1
一文读懂Elephant Swap的LaaS方案的优势之处
[MRCTF2020]PYWebsite 1
Exit login and JSX display
What are Dom and BOM in JS
Gallerycms download, installation and configuration
while循环
「PHP基础知识」使用echo语句输出信息
Plato Farm有望通过Elephant Swap,进一步向外拓展生态
Elment UI usage
使用vertical-align不能让图片和文字垂直居中对齐
背景图片相关应用-铺满,自适应
JS中如何判断一个对象是空对象
[C language switch branch statement and loop statement]
JS基础知识--每日学习总结①








