简体   繁体   中英

Iterate through two JavaScript arrays with an iterator object using next()

I want to compare two sorted JavaScript arrays with custom objects in them and calculate the differences. I would like to do this using iterator objects to walk through them using next() . (Just as it is possible with iterators in Java.) In the MDN it says:

In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. More specifically an iterator is any object which implements the Iterator protocol by having a next() method which returns an object with two properties: value, the next value in the sequence; and done, which is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator's return value. ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators )

Is there any convenient method to gain an iterator object from an array in JavaScript?

Just like for all iterable objects, to obtain an iterator, access its Symbol.iterator property to get the generator, and call it to get the iterator:

 const arr = ['a', 'b', 'c']; const iter = arr[Symbol.iterator](); console.log(iter.next()); console.log(iter.next()); console.log(iter.next()); console.log(iter.next()); 

 const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c']; const iter1 = arr1[Symbol.iterator](); const iter2 = arr2[Symbol.iterator](); console.log(iter1.next()); console.log(iter2.next()); console.log(iter1.next()); console.log(iter2.next()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM