Make An Iterable Object

/*
 * Programming Quiz: Make An Iterable Object
 *
 * Turn the `james` object into an iterable object.
 *
 * Each call to iterator.next should log out an object with the following info:
 *     - key: the key from the `james` object
 *     - value: the value of the key from the `james` object
 *     - done: true or false if there are more keys/values
 *
 * For clarification, look at the example console.logs at the bottom of the code.
 */

const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185
};

let iterator = james[Symbol.iterator]();

console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185

这一题怎么写呀?

相关知识链接:https://segmentfault.com/a/11...
我看了网上的资料,试了好几遍都不对,求大佬们帮忙解决?

阅读 3.3k
2 个回答

链接的文章自己也说了,这个方法仅仅适用于类数组对象...对于普通对象这两个方法是不管用的...上面的代码就会输出三个undefined...上面的代码就会抛异常的
所以你需要用别的方法来实现

var james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]: function*(){for(var prop of Object.getOwnPropertyNames(this)){yield this[prop];}}
};
for(let j of james){
    console.log(j);
}
const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator](){
        let properties = Object.keys(this);
        let index = 0;
        let contex = this;
        return {
          next() {
            return {"value":contex[properties[index]], "key":properties[index], "done":Boolean(index++ >= properties.length - 1) };
          }
        };
    }
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏