微微怪时间不能保存情绪,保存那一切情绪所曾流连的境界。——《你是人间的四月天》
文档
我们可以用其将Iterator
转换为对象,例如Map、Array
或者实现@@iterator
方法的的对象
1 Object .fromEntries (new URLSearchParams ("q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4" ))
1 Object .fromEntries (new Map (new URLSearchParams ("q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4" )))
例如我这里写一个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 ]() { 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" })]
或者我们提到的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" }))
当然还是返回一个对象
甚至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)
我们再写一个无穷迭代器且实现了迭代协议让其变为一个可迭代对象
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++} } } } }
然后我们使用该方法,会造成死循环,因为永远不会结束迭代
另一种写法是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 ); console .log (it.next ().value ); console .log (it.next ().value );
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" })
得到