0

I'm having something strange concerning the length of an array, maybe the problem is obvious and i don't see it. I have an array: this.roles which is an array of simple objects:

this.roles = [
    {
        GRO_id:1,
        ROL_id:1
    }
];

When I add objects in it I use the method push with a new object:

this.roles.push({
    GRO_id: GRO_id,
    ROL_id: ROL_id
});

But when I try to loop on this.roles the script can't seem to go through all objects, so I tried console.log to see what it gives:

console.log(this.roles);                //l.69
console.log(this.roles[0]);             //l.70
console.log(this.roles[1]);             //l.71
console.log(this.roles.length);         //l.72
console.log(this.roles);                //l.73

And here are the results:

[Object]
    0: Object
    1: Object
    length: 2
    __proto__: Array[0]                 //l.69

Object {GRO_id: 1, ROL_id: 1}           //l.70

Undefined                               //l.71

1                                       //l.72

[Object]
    0: Object
    1: Object
    length: 2
    __proto__: Array[0]                 //l.73

Can someone explain to me why I got different length? It's as if the objects were wrapped in a single object, or as if I had accidentally made the variable this.roles reference 2 different arrays...

Jo Pango
  • 474
  • 1
  • 5
  • 15
  • 3
    It seems to work fine for me: http://jsfiddle.net/m0swnkb0/ – Brian Glaz Mar 20 '15 at 15:21
  • 2
    Best guess: [Chrome updates the array after the console.log call](http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays). – JJJ Mar 20 '15 at 15:23
  • 1
    You are most likely adding the array element *after* you are iterating over the array. This is backed by the fact that `this.roles[1]` is `undefined`. `console.log` will however only show the final array. Simple example to reproduce: `var arr = [1]; console.dir(arr); arr.push(2); console.dir(arr);` – Felix Kling Mar 20 '15 at 15:24

0 Answers0