Javascript Object returns junk values

泪湿孤枕 提交于 2019-12-17 21:33:36

问题


I'm trying to assign values to a javascript object and when doing so, some junk values end up in there which seem like array methods like 'push', 'pop','splice' etc. The following is my code.

function myTest(){
var userArray = new Object();
var req = new Request.JSON({
url: '/myTest.php',
method: 'post',
noCache: true,
data: 'userID=999',

onSuccess: function(json){       
    for(var key in json){
      userArray = json[key];
      for (var row in userArray){
        alert(row)   // This returns values like '$family','push','pop', 'reverse' etc.
        }
    }
},
onException: function(xhr){
  alert("Unable to process your request");
},
onFailure: function(xhr){
  alert("Unable to connect to the server");
}
}).send();
}

I am not sure what I'm missing here but it looks like I certainly am. Any help on this would be greatly appreciated.


回答1:


Never use for...in on an array. Period. The garbage values you are seeing are properties of the array prototype.

See this related question.




回答2:


for (var row in userArray){
        if(userArray.hasOwnProperty(row))
           alert(row) ;  
        }

Details here. Basically, for loop will take all available properties/functions. And you must check if it belongs to that object only or is inherited.



来源:https://stackoverflow.com/questions/12285112/javascript-object-returns-junk-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!