关于Javascript Iterator中执行顺序的问题
A question about the execution sequence in Javascript Iterator
class iteratorWithoutG {
[Symbol.iterator]() {
let val = 0;
let threshold = 10;
return {
next() {
if(val >= threshold) {
console.log('iteratorWithoutG is finished');
return {
done: true,
value: undefined
}
}
return {
done: false,
value: val++
}
},
return() {
return {
done: true,
value: undefined
}
}
}
}
}
const iWithoutG = new iteratorWithoutG(10);
console.log([...iWithoutG]);
我在学习有关 JS 迭代器的东西,我得到了这个:
iteratorWithoutG is finished
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
我想知道为什么String显示在Array之前,所以我添加了一些日志:
class iteratorWithoutG {
[Symbol.iterator]() {
let val = 0;
let threshold = 10;
return {
next() {
if(val >= threshold) {
console.log('iteratorWithoutG is finished');
console.log(Date.now())
return {
done: true,
value: undefined
}
}
return {
done: false,
value: (val++, Date.now())
}
},
return() {
return {
done: true,
value: undefined
}
}
}
}
}
这次我收到这条消息:
iteratorWithoutG is finished
1610466807875
[ 1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872 ]
所以字符串其实是在Array之后生成的,但是怎么显示在Array之前呢??阵列存储在某处吗?
这一行:
console.log([...iWithoutG]);
脱糖至:
{
let arr = [];
for (const e of iWithoutG) {
arr.push(e);
}
console.log(arr);
}
这意味着首先创建并填充数组,然后才调用 console.log()
。所以迭代器在调用 console.log()
.
之前完成
完整的事件顺序:
- 数组和迭代器被初始化。
- 调用迭代器的
next()
方法,直到完成并将结果推入数组。
- 迭代器完成。
- 数组被记录到控制台。
class iteratorWithoutG {
[Symbol.iterator]() {
let val = 0;
let threshold = 10;
return {
next() {
if(val >= threshold) {
console.log('iteratorWithoutG is finished');
return {
done: true,
value: undefined
}
}
return {
done: false,
value: val++
}
},
return() {
return {
done: true,
value: undefined
}
}
}
}
}
const iWithoutG = new iteratorWithoutG(10);
console.log([...iWithoutG]);
我在学习有关 JS 迭代器的东西,我得到了这个:
iteratorWithoutG is finished
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
我想知道为什么String显示在Array之前,所以我添加了一些日志:
class iteratorWithoutG {
[Symbol.iterator]() {
let val = 0;
let threshold = 10;
return {
next() {
if(val >= threshold) {
console.log('iteratorWithoutG is finished');
console.log(Date.now())
return {
done: true,
value: undefined
}
}
return {
done: false,
value: (val++, Date.now())
}
},
return() {
return {
done: true,
value: undefined
}
}
}
}
}
这次我收到这条消息:
iteratorWithoutG is finished
1610466807875
[ 1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872,
1610466807872 ]
所以字符串其实是在Array之后生成的,但是怎么显示在Array之前呢??阵列存储在某处吗?
这一行:
console.log([...iWithoutG]);
脱糖至:
{
let arr = [];
for (const e of iWithoutG) {
arr.push(e);
}
console.log(arr);
}
这意味着首先创建并填充数组,然后才调用 console.log()
。所以迭代器在调用 console.log()
.
完整的事件顺序:
- 数组和迭代器被初始化。
- 调用迭代器的
next()
方法,直到完成并将结果推入数组。 - 迭代器完成。
- 数组被记录到控制台。