如何在Javascript中创建可迭代对象

Fat*_*sny 4 javascript ecmascript-6

我有一个像这个let Lila = { name: 'Lila', height:5'10" 的javascript对象, weight: 185} 我想使用next()迭代它

Nin*_*olz 8

您可以Symbol.iterator使用迭代器为对象分配属性.

了解更多关于使用iterator.next迭代的协议.

let lila = { name: 'Lila', height: '5\'10"', weight: 185 };

lila[Symbol.iterator] = function* () {
    var k;
    for (k in this) {
        yield [k, this[k]];
    }
};

var iterator = lila[Symbol.iterator]();

console.log(iterator.next()); // get the first of a sequence of values

console.log([...lila]);       // get all key/values pairs
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)


Fat*_*sny 4

这是答案

const Lila = {
    name: 'Lila',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]() {
        let index = 0; // use index to track properties 
        let properties = Object.keys(this); // get the properties of the object 
        let Done = false; // set to true when the loop is done 
        return { // return the next method, need for iterator 
            next: () => {
                Done = (index >= properties.length);
                // define the object you will return done state, value eg Lila ,key eg 
                //name
                let obj = {
                    done: Done,
                    value: this[properties[index]],
                    key: properties[index]
                };
                index++; // increment index
                return obj;
            }
        };
    }
};
Run Code Online (Sandbox Code Playgroud)