使用next()时如何清除Iterable对象的当前位置?

时间:2017-02-23 08:57:44

标签: javascript ecmascript-6

如何在for循环后或使用.next()方法后清除当前位置?

 const arr = [1,4,2];
 for(v of arr){
     // console.log(v); // 1 4 2
 }
 //  console.log(arr.next())  //arr.next is not a function

 /*
 * 
 * Why? because it is an iterable not an iterator,
 * and to be able to use .next we need to call the iterator method 
 * this iterable’s Symbol.iterator returns:
 * */
 const iter = arr[Symbol.iterator]();

 console.log(iter.next());
 console.log(iter.next());
 console.log(iter.next());
 console.log(iter.next());

在此之后,我想从item获得1个值。

怎么做?

此示例来自http://blog.dubizzle.com/boilerroom/2017/01/09/introduction-javascript-iterables-iterators-generators/

1 个答案:

答案 0 :(得分:1)

本身无法“清除当前位置”。但是,在这个答案中提出了有用的替代方案:Is it possible to reset an ECMAScript 6 generator to its initial state?