一、通过本文可以学到的知识
1 学习元编程[Symbol.iterator]
2 学习对象的for of循环
3 学习链表结构
下面先看下yocto-queue的源码
class Node {
value;
next;
constructor(value) {
this.value = value;
}
}
export default class Queue {
#head;
#tail;
#size;
constructor() {
this.clear();
}
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
clear() {
this.#head = undefined;
this.#tail = undefined;
this.#size = 0;
}
get size() {
return this.#size;
}
* [Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
}
二、[Symbol.iterator] 使用
可以在类或对象中使用[Symbol.iterator]来定义迭代:
class MockFoo {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
}
const mockObj = {
*[Symbol.iterator]() {
yield "a";
yield "b";
},
};
console.log(...new MockFoo()); // 1, 2, 3
console.log(...mockObj); // 'a', 'b'
三、使用for of 遍历对象
通过添加[Symbol.iterator]属性,这样使用for of遍历的时候直接走这个属性函数就可以了
let obj = {
name: "zhang san",
age: 19,
};
obj[Symbol.iterator] = function* fun() {
yield this['name'];
yield this['age'];
};
console.log(obj);
for (let i of obj) {
console.log(i); // zhang san 19
}
四、链表数据结构
就如我们开头的代码,这里就不粘贴代码了
1 每次有一个新的数据都会创建一个node
2 第一次会将node给到#head和#tail,其实他们此时指向的是同一个对象,这个对象改变了,他们两个就都改变了
3 当再次有新的node进来的时候会将新的node给到#tail.text的,这样以此类推下去
五、测试
const queue = new Queue();
queue.enqueue('zhang san');
queue.enqueue('li si');
queue.enqueue('wang wu');
queue.enqueue('zhao liu');
console.log('queue',queue);
最后的结果是这样的
使用for of进行循环
for(let i of queue){
console.log('i',i);
}
最后的结果为:
大家喜欢就点点关注吧。