开发者问题收集

使用迭代器对象 next() 遍历两个 JavaScript 数组

2019-08-07
361

我想比较两个已排序的 JavaScript 数组,其中包含自定义对象,并计算差异。我想使用迭代器对象来执行此操作,使用 next() 遍历它们。(就像 Java 中的迭代器一样。)在 MDN 中,它说:

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 )

是否有任何方便的方法可以从 JavaScript 中的数组中获取迭代器对象?

1个回答

与所有可迭代对象一样,要获取迭代器,请访问其 Symbol.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());
CertainPerformance
2019-08-07