이터레이터에 대해 알아보기
이터레이터란 무엇인가요?
- 사용자가 컨테이너 객체를 순회하는 객체인 이터레이터는 객체의 내부 구현 세부 사항에 대한 걱정 없이 이 인터페이스를 사용합니다.
- 데이터베이스의 커서처럼 작동하며 다양한 프로그래밍 언어(예: Java, Python)에는 반복기가 있습니다.
- 반복기의 역할은 특정 데이터 구조에서 객체를 순회하는 데 도움을 주는 것입니다.
자바스크립트에서 이터레이터는 이터레이터 프로토콜을 준수해야 하는 구체적인 객체입니다.
- 반복자 프로토콜은 일련의 값을 생성하는 표준 방법을 정의합니다;
- 자바스크립트의 이 표준은 구체적인 다음 방법입니다;
다음 방법의 요구 사항
매개 변수가 없거나 매개 변수가 하나뿐인 함수, 팬유 다음 두 가지 속성을 가진 객체입니다:
완료
- 반복자가 시퀀스의 다음 값을 먼저 가져올 수 있으면 거짓입니다.
- 이터레이터가 시퀀스 반복을 완료한 경우 TRUE(이 경우 값은 선택 사항이며, 여전히 존재하는 경우 반복이 완료된 후 기본 반환 값)입니다.
값
- 반복자가 반환하는 모든 자바스크립트 값입니다. done는 TRUE이면 생략할 수 있습니다.
const friends = ["1","2","3","4"]
let index = 0
const friendIterator = {
next: function (){
if (index < friends.length) {
return {
value: friends[index++],
done: false
}
} else {
return {
value: undefined,
done: true
}
}
}
}
console.log(friendIterator.next()) //{ value: '1', done: false }
console.log(friendIterator.next()) //{ value: '2', done: false }
console.log(friendIterator.next()) //{ value: '3', done: false }
console.log(friendIterator.next()) //{ value: '4', done: false }
console.log(friendIterator.next()) //{ value: undefined, done: true }
const friends = ["1","2","3","4"]
let index = 0
function createArrayIterator(arr) {
return {
next: function (){
if (index < arr.length) {
return {
value: arr[index++],
done: false
}
} else {
return {
value: undefined,
done: true
}
}
}
}
}
const friendIterator = createArrayIterator(friends)
console.log(friendIterator.next()) //{ value: '1', done: false }
console.log(friendIterator.next()) //{ value: '2', done: false }
console.log(friendIterator.next()) //{ value: '3', done: false }
console.log(friendIterator.next()) //{ value: '4', done: false }
console.log(friendIterator.next()) //{ value: undefined, done: true }
이터러블 객체(컴퓨팅)
객체가 이터러블 프로토콜을 구현하면 이터러블 객체입니다.
이 객체의 요구 사항은 @@iterator 메서드를 구현하고 코드에서 Symbol.iterator를 사용하여 프로퍼티에 액세스해야 한다는 것입니다;
이터러블 객체의 이점
- 객체가 이터러블이 되면 특정 반복 연산을 수행할 수 있습니다;
- 예를 들어, for... 연산은 실제로 @@이터레이터 메서드를 호출합니다.
이터러블 객체 코드:
const info = {
friends: ['lisi', 'wangwu', 'tanakasan'],
[Symbol.iterator]: function () {
let index = 0;
return {
next: function () {
if (index < this.friends.length) {
return {
value: this.friends[index++],
done: false
}
} else {
return {
value: undefined,
done: true
}
}
}
}
}
}
네이티브 이터레이터 객체
실제로 일반적으로 생성되는 많은 네이티브 객체는 이미 이터레이터 객체를 생성하는 이터러블 프로토콜을 구현하고 있습니다:
- 문자열, 배열, 맵, 집합, 인수 객체, 노드 목록 컬렉션;
// 배열 자체가 이터러블 객체인 경우
let nums = [0, 1, 0, 3, 12]
// 이터러블 함수 가져오기
console.log(nums[Symbol.iterator]) // console.log(nums)
// 이터러블 함수를 호출하고 이터레이터를 가져옵니다.
const iterator = nums[Symbol.iterator]()
console.log(iterator.next())//{ value: 0, done: false }
console.log(iterator.next())//{ value: 1, done: false }
console.log(iterator.next())//{ value: 0, done: false }
console.log(iterator.next())//{ value: 3, done: false }
console.log(iterator.next())//{ value: 12, done: false }
console.log(iterator.next())//{ value: undefined, done: true }
이터러블 객체 적용
그렇다면 이런 것들을 어디에 사용할 수 있을까요?
- 자바스크립트 구문: ....의, 확장 구문, 산출*, 해체된 할당
사용자 지정 클래스 반복
- 객체 지향 개발에서는 클래스를 통해 자신만의 클래스를 정의할 수 있으며, 이 클래스는 많은 객체를 생성할 수 있습니다.
- 사용자 정의 클래스에서 생성된 객체를 기본적으로 이터러블하게 하려면 클래스를 디자인할 때 @@iterator 메서드를 추가하면 됩니다.
Case
- 교실에는 교실 위치, 이름 및 현재 교실 학생이 있습니다;
- 이 강의실은 새 학생을 위한 준비가 완료되었습니다.
- 생성된 클래스룸은 반복 가능한 객체입니다.
class Classroom {
constructor(name, address, initialStudent) {
this.name = name;
this.address = address;
this.students = initialStudent;
}
push(student) {
this.students.push(student);
}
[Symbol.iterator]() {
let index = 0
return {
next: () => {
if (index < this.students.length) {
return {value: this.students[index++], done: false}
} else {
return {value: undefined, done: true}
}
}
}
}
}
const classroom = new Classroom("3학년 1반", "시위안 빌딩 301호", ["작은 빨간색", "", "작은 노란색"])
const classroom1 = new Classroom("3학년 2반", "시위안 빌딩 302호", ["littleblue", "littlegreen", "littlegreen"])
for (const stu of classroom1) {
console.log(stu)
}
for (const stu of classroom) {
console.log(stu)
}
이터레이터 터미널
경우에 따라 반복기가 완전히 반복되지 않고 중단될 수 있습니다:
- 예를 들어 트래버스는 중단, 반환, 던지기를 통해 루핑 연산을 중단합니다;
- 예를 들어, 디컨스트럭션할 때 모든 값이 디컨스트럭션되는 것은 아닙니다;





