奇怪的行为 "for in" 语句 (NodeJS)

Strange behaviour "for in" statement (NodeJS)

我想我错过了 "for in" 语句的使用。 我有一个从 mongoDB 查询(nodejs + 猫鼬)返回的 JSON 文档,他的结构如下所示:

  [{  
  "_id":"596f2f2ffbf8ab12bc8e5ee7",
  "date":"1500458799794",
  "questionId":4249,
  "__v":0,
  "myArray":[  
     "1234567",
     "8901234",
     "5678901"
     ]
  },
  {  
  "_id":"596f2f2ffbf8ab12bc8e5ee5",
  "date":"1500458799795",
  "questionId":4245,
  "__v":0,
  "myArray":[  
     "1234565",
     "5678905"
     ]
  }]

在 "for in" cicle 中,我获取每个文档并进入另一个我想迭代数组 "myArray"。问题是当我尝试迭代数组 "myArray" 时。如果我用 "for in" 语句迭代它,我会收到很多其他错误的东西,比如我正在迭代查询返回的文档:

  [null,{},{"_id":"596f2f2ffbf8ab12bc8e5ee7","date":"1500458799794","questionId":4249,"__v":0,"myArray"["1234567","8901234","5678901"]},null,null,....,"myArray",true,[],{"caster":{"enumValues":[],"regExp":null,"path":"myArray","instance":"String","validators":[],"setters":[],"getters":[],"options":{},"_index":null},"path":"whoDislikes","instance":"Array"....etc etc... ]

如果我用经典的 for 语句迭代它,一切都很好: ["1234567","8901234","5678901"]

为什么? 代码如下:

  for(question in data){
      var myArray=data[question].myArray;
      console.log(JSON.stringify(myArray));   //this print ["1234567","8901234","5678901"]

      for(var i=0;i<myArray.length;i++){
         console.log(myArray[i]);   //this print ["1234567","8901234","5678901"]
       }
       for(element in myArray){
          console.log(myArray[element]);   //this print a lot of wrong stuff!
       }
  }

这是因为 Mongoose returns 一个文档,所以您看到的属性是原型链更上层的属性。

我认为您要么需要在 for...in 循环中进行 hasOwnProperty 测试,要么使用经典循环,要么使用 myArray.forEach(function (element) {});