JavaScriptイテレータの実用的な説明
17725 ワード
イテレータとは何か
Iterators 素地の用語では、オブジェクトのコレクションを反復処理するために使用されます.イテレータはES 6(ECMASCRIPT 6)の特徴であり、それは休止されることができる先進のループです、反復子はシーケンスの次の項目を返すNext ()メソッドを提供します、値プロパティは現在のアイテムの値にアクセスすることができます.
以下の例です
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
上のコードから、最初の4つの呼び出しで配列内の最初の4つの項目の値が表示され、最後に未定義の値が返されます.これは反復処理が終了したときに反復配列が終了したためです.以下はコンソール出力です
私はデモアプリケーションを構築することによって実際にイテレータを説明するので、それは私たちのイテレータは、現実世界のアプリケーションで使用されているの概要を与える、このアプリでは、私はからデータを取得されます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、および型にアクセスできます.以下はブラウザの出力です
ノート
我々もGenerators , でもGenerators イテレータとは少し異なりますが、フェッチされるデータを作成することもできます.また、外部のAPIからデータを取得することもできます.
こちらがlink アプリに
読んで、ハッピーコーディングありがとう!
Reference
この問題について(JavaScriptイテレータの実用的な説明), 我々は、より多くの情報をここで見つけました https://dev.to/bjhaid_93/practical-explanation-of-javascript-iteratorswith-a-demo-app-o95テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol