奇怪的行为"对于"声明(NodeJS)

时间:2017-07-19 11:34:31

标签: javascript arrays node.js mongodb for-in-loop

我想我错过了使用" for in"声明。 我有一个从mongoDB查询(nodejs + mongoose)返回的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"。如果我用"迭代它"声明我收到很多其他错误的东西,比如我正在迭代查询返回的文档:

  [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!
       }
  }

1 个答案:

答案 0 :(得分:2)

这是因为Mongoose会返回一个Document,因此您看到的属性是原型链中的那些属性。

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