1

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.

Nash3man
  • 155
  • 1
  • 4
  • 15
  • 1
    What you have posted there is a syntax error. Please post your actual code to avoid wasting everybody's time. – Pointy Sep 05 '12 at 15:43
  • You can remove them by checking `if (json.hasOwnProperty(key))` inside your loop. – Matt Sep 05 '12 at 15:45
  • @Pointy. Sorry about that :) Thank you Matt. – Nash3man Sep 05 '12 at 15:53
  • Well it's still syntactically incorrect. It looks like a jumble of object literal notation and part of a function declaration. – Pointy Sep 05 '12 at 15:57
  • @Pointy I'm not sure what's wrong here but that's all I have and I didn't want to paste the entire code which would be confusing. Thanks. – Nash3man Sep 05 '12 at 16:21

2 Answers2

3

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

See this related question.

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • Thank you jbabey. That was my bad to have missed it. This solved it. Appreciate your extremely quick response :) – Nash3man Sep 05 '12 at 15:51
1
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.

Viktor S.
  • 12,736
  • 1
  • 27
  • 52