微微怪时间不能保存情绪,保存那一切情绪所曾流连的境界。——《你是人间的四月天》

文档

我们可以用其将Iterator转换为对象,例如Map、Array或者实现@@iterator方法的的对象

1
Object.fromEntries(new URLSearchParams("q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4"))

image-20220402132501540

1
Object.fromEntries(new Map(new URLSearchParams("q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4")))

image-20220402132519763

例如我这里写一个class,实现迭代协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Ruben {
constructor(data) {
this.data = data
this.dataArray = Object.entries(data)
}

[Symbol.iterator]() {
// Use a new index for each iterator. This makes multiple
// iterations over the iterable safe for non-trivial cases,
// such as use of break or nested looping over the same iterable.
let index = 0;

return {
next: () => {
if (index < this.dataArray.length) {
return {value: this.dataArray[index++], done: false}
} else {
return {done: true}
}
}
}
}
}

然后我们就可以把其作为一个迭代器使用,例如散列运算符

1
2
3
4
5
6
7
8
[...new Ruben({
"q": "apple",
"from": "en",
"to": "zh",
"appid": "2015063000000001",
"salt": "1435660288",
"sign": "f89f9594663708c1605f3d736d01d2d4"
})]

image-20220402125759466

或者我们提到的Object.fromEntries

1
2
3
4
5
6
7
8
Object.fromEntries(new Ruben({
"q": "apple",
"from": "en",
"to": "zh",
"appid": "2015063000000001",
"salt": "1435660288",
"sign": "f89f9594663708c1605f3d736d01d2d4"
}))

当然还是返回一个对象

image-20220402131805240

甚至for..of

1
2
3
4
5
6
7
8
for (let i of  new Ruben({
"q": "apple",
"from": "en",
"to": "zh",
"appid": "2015063000000001",
"salt": "1435660288",
"sign": "f89f9594663708c1605f3d736d01d2d4"
}))console.log(i)

image-20220402132155602

我们再写一个无穷迭代器且实现了迭代协议让其变为一个可迭代对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class SimpleClass {
constructor(data) {
this.data = data
}

[Symbol.iterator]() {
let index = 0;
return {
next: () => {
return {value: index++}
}
}
}
}

然后我们使用该方法,会造成死循环,因为永远不会结束迭代

1
[...new SimpleClass()]

另一种写法是function形式

1
2
3
4
5
6
7
8
9
10
11
function idMaker() {
let index = 0;
return {
next: function() {
return {
value: index++,
done: false
};
}
};
}

使用起来差不多:

1
2
3
4
5
let it = idMaker();

console.log(it.next().value); // '0'
console.log(it.next().value); // '1'
console.log(it.next().value); // '2'

fromEntries是将迭代器转为对象,也可以用Object.entries将对象转换为数组

1
2
3
4
5
6
7
8
Object.entries({
"q": "apple",
"from": "en",
"to": "zh",
"appid": "2015063000000001",
"salt": "1435660288",
"sign": "f89f9594663708c1605f3d736d01d2d4"
})

得到

image-20220402125759466