当前位置:网站首页>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);
}
边栏推荐
猜你喜欢
随机推荐
背景图片相关应用-铺满,自适应
Permission display - dynamic list on the left
路由的配置和前往登录首页进行发送请求
页面布局中元素定位的几种方式
js中isNaN和Number.isNaN的区别
Edit delete user
==,===,Object.is
JS中for...of和for...in的区别
store redux在项目中的应用
My first blog
「PHP基础知识」PHP语句和语句块
洛谷超级玛丽游戏
Share a multiple-choice question about define (including the replacement rules, program environment and preprocessing related knowledge of define during precompiling)
「PHP基础知识」PHP中实现数学运算
Package JWT
页面的基本布局
First knowledge of C language -- constants and variables
Construction of layout and display of weather forecast
MD5 password encryption
一本通1353——表达式括号匹配(栈)








