如果我们有:令 myArr = [1, 2, 3, 4] ,如果我们这样做: myArr.values();我们将得到 Array Iterator [1, 2, 3, 4]。 那么,数组和数组迭代器有什么区别呢?
最佳答案
它们有不同的目的和功能:
- 数组是房间,迭代器是房间守卫,允许移动到下一个房间
- Iterator 允许您遍历,例如next() 可以被调用
- Iterator 不允许您通过索引访问,例如迭代器[0]
const x = [1, 2, 3];
const iterator = x.values();
console.log(x[1]); //OK -> 2
console.log(iterator[1]); // -> Undefined
console.log(iterator.next()); //OK -> 1
console.log(iterator.next()); //OK -> 2
console.log(iterator.next()); //OK -> 3
console.log(iterator.next()); //OK -> { value: undefined, done: true }
//x.next(); //✗Error: x.next is not a function
关于javascript - JS中真正的数组和数组迭代器有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58667005/