javascript迭代对象
时间: 2023-11-19 22:44:42 浏览: 45
迭代对象是指在JavaScript中可以通过for...of循环进行遍历的对象。为了使一个对象成为可迭代对象,它必须具有一个名为[Symbol.iterator]的方法。这个方法返回一个迭代器对象,该对象定义了如何遍历迭代对象的规则。
为了简化代码,我们可以将[Symbol.iterator]方法写入对象中。例如,我们可以创建一个名为number的可迭代对象,其中包含一个[Symbol.iterator]方法,该方法定义了从5到10的遍历规则。然后,我们可以使用for...of循环遍历number对象并打印每个值。
```javascript
let number = {
from: 5,
to: 10,
[Symbol.iterator]() {
this.current = this.from;
return this;
},
next() {
if (this.current <= this.to) {
return { done: false, value: this.current };
} else {
return { done: true };
}
}
};
for (let s of number) {
console.log(s);
}
```
此外,我们还可以自己编写一个迭代器函数来指定对象的遍历规则。例如,我们可以创建一个名为range的对象,并在它的[Symbol.iterator]方法中定义从1到5的遍历规则。然后,我们可以使用for...of循环遍历range对象并打印每个值。
```javascript
let range = {
from: 1,
to: 5,
[Symbol.iterator]() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return { done: false, value: this.current };
} else {
return { done: true };
}
}
};
}
};
for (let num of range) {
console.log(num);
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)