简体   繁体   English

使普通对象可迭代。(javascript)

[英]Making plain objects iterable.(javascript)

So I'm working on a personal project after covering the first seven chapters of eloquent javascript by Marjin Heverbeke.因此,在完成 Marjin Heverbeke 的 eloquent javascript 的前七章之后,我正在着手一个个人项目。 Im creating school data handling system.我正在创建学校数据处理系统。 So i already made my data structure which includes a lot of objects, so I created a test object to so that i could practice the iteration protocol, this is what i wrote所以我已经制作了包含很多对象的数据结构,所以我创建了一个测试对象,以便我可以练习迭代协议,这就是我写的

let object = {a:'a',b:'b',c:'c',d:'d',e:'e'};
object[Symbol.iterator]=function(){
    let keys = Object.keys(this);
    let count=0;
return {
    next(){
        if(count>keys.length){
            return {value: null, done:true};
        }
        else{
            let value=this[keys[count]];
            count++;
            return {value, done:false};
        }
    }
}
}

but when i do this但是当我这样做时

    for(let each of object){
       console.log([each]);
}

it outputs它输出

//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]

I don't know what is wrong oo, pls help.我不知道有什么问题哦,请帮忙。

Try this:尝试这个:

let object = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
  e: 'e',
};
object[Symbol.iterator] = function () {
  let keys = Object.keys(this);
  let count = 0;
  return {
    next() {
      if (count === keys.length) {
        return {
          value: null,
          done: true,
        };
      }
      let value = keys[count];
      count++;
      return {
        value,
        done: false,
      };
    },
  };
};

for (let each of object) {
  console.log([each]);
}

Note the errors were: let value=this[keys[count]];注意错误是: let value=this[keys[count]]; and if (count > keys.length)if (count > keys.length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用普通的javascript / jquery在数组内制作对象 - Making objects inside an array using plain javascript/jquery 使用普通 Javascript 进行计算 - Making calulation with Plain Javascript 为什么对象在 JavaScript 中不可迭代? - Why are Objects not Iterable in JavaScript? ERROR 错误:未捕获(承诺):TypeError:this.products 不可迭代。 (但它是可迭代的) - ERROR Error: Uncaught (in promise): TypeError: this.products is not iterable. (but it is iterable) “订阅字段必须返回异步可迭代。 收到:未定义” - apollo “Subscription field must return Async Iterable. Received: undefined” 在javascript中使对象变为非全局对象 - Making objects nonGlobal in javascript `Duplex.from()` 抛出`“可迭代”参数必须是可迭代的实例。 接收到 Object 的实例 - `Duplex.from()` throws `The "iterable" argument must be an instance of Iterable. Received an instance of Object` 普通Javascript对象上的jQuery.bind()事件 - jQuery.bind() events on plain Javascript objects 为什么 2 个空 JavaScript 函数或普通对象不相等 - Why are 2 empty JavaScript functions or plain objects not equal 测试返回不同对象的纯JavaScript文件 - Test plain javascript file returning different objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM