JavaScript 迭代器的实际应用讲解(附示例应用)
由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!
什么是迭代器?
简单来说,迭代器用于遍历对象集合。迭代器是 ES6(ECMAScript 6)的特性,它是一种高级循环,可以暂停。迭代器提供 `next()` 方法,该方法返回序列中的下一个元素。`value` 属性可用于访问当前元素的值。当 `next()` 方法返回一个 `done` 属性设置为 `true` 的对象时,迭代器即被视为终止。
以下是一个示例。
function Iterator(names){
//set the index to 0
let nextIndex = 0;
return {
next() {
return nextIndex < names.length
?
{value:names[nextIndex++], done:false}
:
{done:true}
}
}
}
//Create an array
let names = ['wale', 'ali', 'john', 'bubu'];
//pass the array into the Iterator function
let name = Iterator(names);
console.log(name.next().value);//wale
console.log(name.next().value);//ali
console.log(name.next().value);//john
console.log(name.next().value);//bubu
console.log(name.next().value);//undefined
从上面的代码可以看出,前四次调用返回数组中前四个元素的值,最后一次调用返回 undefined,因为数组中已经没有元素可以遍历,迭代终止。
以下是控制台输出。
我将通过构建一个演示应用程序来实际讲解迭代器,以便我们了解迭代器在实际应用中的用途。在这个应用程序中,我将从https://api.github.com/users获取数据,这将使我们能够查看前 46 位用户的个人资料。
以下是 HTML 结构。
<!doctype html>
<html lang="en">
<head>
<title>Profile Scroller</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto text-center">
<h1 class="mb-3">Profile Scroller</h1>
<div id="imageDisplay"></div>
<br>
<div id="profileDisplay"></div>
<br>
<button id="next" class="btn btn-dark btn-block">Next</button>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
</html>
以下是 Javascript 代码
//create the function
function Iterator(profile) {
//set the index to 0
let nextIndex = 0;
return {
next() {
return nextIndex < profile.length
?
{value: profile[nextIndex++], done: false}
:
{done: true}
}
}
}
//html classes and ids stored in object
let selector = {
next : 'next',
profile : 'profileDisplay',
image: 'imageDisplay'
}
//Using AJAX to fetch data
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.github.com/users', true);
xhr.onload = function() {
if (this.status === 200) {
let data = JSON.parse(this.responseText);
//pass the data coming in from the API into the iterator function
let profile = Iterator(data);
//call the load function to load the first profile
loadProfile();
//create an event listener for the button
document.getElementById(selector.next).addEventListener('click', loadProfile);
function loadProfile() {
//get the value of the current and next data
const currentProfile = profile.next().value
//check if the current value is not undefined
if(currentProfile !== undefined){
document.getElementById(selector.profile).innerHTML =
`<ul class="list-group">
<li class="list-group-item">Login: ${currentProfile.login}</li>
<li class="list-group-item">Id: ${currentProfile.id}</li>
<li class="list-group-item">Type: ${currentProfile.type}</li>
</ul>
`
document.getElementById(selector.image).innerHTML = `<img src="${currentProfile.avatar_url}" class="w-25">`;
}
else {
//reload the page after the last iteration
window.location.reload();
}
}
}
}
xhr.send()
在上面的代码中,创建了迭代器函数,将从API获取的数据传递给迭代器函数,从API我们可以访问浏览器中显示的头像、登录名、ID 和类型,在最后一次迭代之后,页面重新加载,并再次调用 loadProfile 函数。
笔记
我们也有生成器,但生成器与迭代器略有不同。生成器可以获取自己创建的数据,也可以从任何外部 API 获取数据。
这是应用的链接
。感谢阅读,祝您编程愉快!
