发布于 

迭代器实现array和对象遍历

迭代数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//迭代数组
var something = (function(array){
var arr = array //数组
var nextVal; //遍历的下个值
var i = 0; //用作数组索引

return {
[Symbol.iterator]:function(){
return this;
},

next:function(){
var done = false;
if(i < arr.length){
nextVal = array[i];
}else{
done = true;
}


i++
return {done:done, value:nextVal}
}
}
})([10,50,99,-1]) //传入数组
//进行迭代
for(let j of something){
console.log(j)
}

迭代对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//迭代对象
var person = {
name:'zhangs',
age:18,
sex:'male'
}

var another = (function(obj){
var obj = obj; //对象
var nextVal; //遍历的下一个值
var propertyList = Object.keys(obj); //获取所有键,并以数组形式返回
var i = 0; //数组见的索引

return {
[Symbol.iterator]:function(){return this},
next:function(){
var done = false
if(i < propertyList.length){
//每对键值都是一个对象
nextVal = {}
var proName = propertyList[i]
nextVal[proName] = obj[propertyList[i]]
}else{
done = true
}
i++
return {done:done,value:nextVal}
}
}

})(person) //传入对象
//进行迭代
for(let j of another){
console.log(j)
}


for(let j of another){
console.log(j)
}