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



我想我错过了"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"中,我获取每个文档,并在另一个文档中迭代数组"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 返回一个文档,所以你看到的属性是原型链上更靠后的属性。

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

最新更新