迭代可迭代对象的推荐方法是使用 for..of 循环对象本身,如下所示:
const a = [ 'one', 'two', 'three' ];
for(const item of a)
console.log(item);
我一直在尝试迭代,发现以下内容也可以得到完全相同的结果:
const a = [ 'one', 'two', 'three' ];
let iter = a[Symbol.iterator]();
for(const item of iter)
console.log(item);
即使这样也有效:
const a = [ 'one', 'two', 'three' ];
let iter = a[Symbol.iterator]();
let iter2 = iter[Symbol.iterator]();
for(const item of iter2)
console.log(item);
关于 for..of 循环,我没有看到迭代迭代器而不是可迭代的建议。例如,参见 MDN 中的 for..of。
以这种方式迭代是否合法?