Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

可迭代对象 #5

Open
TieMuZhen opened this issue Nov 13, 2021 · 0 comments
Open

可迭代对象 #5

TieMuZhen opened this issue Nov 13, 2021 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

TieMuZhen commented Nov 13, 2021

ES6 规定,默认的Iterator接口部署在数据结构的Symbol.iterator属性。也就是说,一个数据结构只要具有Symbol.iterator属性(Symbol.iterator方法对应的是遍历器生成函数,返回的是一个遍历器对象),那么就可以其认为是可迭代的。

可迭代对象的特点

  • 具有Symbol.iterator属性,Symbol.iterator()返回的是一个遍历器对象
  • 可以使用for ... of进行循环
  • 通过被Array.from转换为数组
let arry = [1, 2, 3, 4];
let iter = arry[Symbol.iterator]();
console.log(iter.next()); // { value: 1, done: false }
console.log(iter.next()); // { value: 2, done: false }
console.log(iter.next()); // { value: 3, done: false }
console.log(iter.next()); // { value: 4, done: false }
console.log(iter.next()); // {value: undefined, done: true}

为对象添加Iterator 接口

function buildIterator (obj) {
    return {
        ...obj,
        [Symbol.iterator] () {
            const self = this;
            const keys = Object.keys(self);
            let index = 0;
            return {
                next () {
                    if (index < keys.length) {
                        return {
                            value: self[keys[index++]],
                            done: false
                        }
                    } else {
                        return {
                            value: undefined,
                            done: true
                        }
                    }
                }
            }
        }
    };
}

测试

let obj = {
    name: 'hah',
    age: 14
}
let iter = buildIterator(obj);
let list = iter[Symbol.iterator]();

console.log(list.next()); // { value: 'hah', done: false }
console.log(list.next()); // { value: 14, done: false }
console.log(list.next()); // { value: undefined, done: true }

for (let item of obj) {
    console.log(item); // TypeError: obj is not iterable
}

for (let item of iter) {
    console.log(item);
}
// hah
// 14

原生具有Iterator接口的数据结构:

  • Array
  • Map
  • Set
  • String
  • 函数的 arguments 对象
  • TypedArray
  • NodeList 对象
@TieMuZhen TieMuZhen changed the title 可迭代对象有哪些特点 可迭代对象 Nov 13, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant