我想我錯過了「for in」語句的用法。 我有一個JSON文件從MongoDB的查詢返回(的NodeJS +貓鼬),他的結構是這樣的:奇怪的行爲「在」聲明(NodeJS)
[{
"_id":"596f2f2ffbf8ab12bc8e5ee7",
"date":"1500458799794",
"questionId":4249,
"__v":0,
"myArray":[
"1234567",
"89",
"5678901"
]
},
{
"_id":"596f2f2ffbf8ab12bc8e5ee5",
"date":"1500458799795",
"questionId":4245,
"__v":0,
"myArray":[
"1234565",
"5678905"
]
}]
在「在」 cicle我得到的每一個文件,到另一個我要遍歷數組「myArray」。問題是當我嘗試迭代數組「myArray」。如果我重複它「對」的聲明,我收到了很多其他的錯誤的東西,就像如果我循環查詢返回的文件:如果我有一個經典的遍歷它
[null,{},{"_id":"596f2f2ffbf8ab12bc8e5ee7","date":"1500458799794","questionId":4249,"__v":0,"myArray"["1234567","89","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","89","5678901"]
爲什麼? 代碼如下:
for(question in data){
var myArray=data[question].myArray;
console.log(JSON.stringify(myArray)); //this print ["1234567","89","5678901"]
for(var i=0;i<myArray.length;i++){
console.log(myArray[i]); //this print ["1234567","89","5678901"]
}
for(element in myArray){
console.log(myArray[element]); //this print a lot of wrong stuff!
}
}
'對... in'在所有迭代*對象屬性*,不只是數組中indicies。包括任何原型鏈。人們通常不會以這種方式編寫JavaScript(將數組視爲對象),並且部分出於這個原因,使用不太容易出錯的Array.prototype.map和Array.prototype.forEach函數。 –