javascript - JSON array zero length even with elements? -


i getting json response server , creating javascript object. structure this:

var response = {     key1:[],     key2:[],     key3:[],     key4:[],     key5:[] } 

when request completes response object completed this:

object (*expandable):     key1: array[0]     key2: array[0]     key3: array[0]     key4: array[20]     key5: array[113] 

now later on want store information database. have created function , console.log response object make sure it's ok (here getting interesting - see comments):

function setupdatabase(){     console.log(response); // prints response correctly (see response above)     console.log(response.key5); //prints key5: array[0]. if expand array[0] elements inside.     console.log("key5: "+response.key5.length);//prints 0!! } 

it's normal first 3 keys 0 because there no elements returned them. rest 2 ok. why log, while run 3 console.log commands on same object in row? missing something?

this issue how console.log works on browsers. might @ using console.log(json.stringify(response.key5)) instead, point-in-time view.

basically, console.log logs top level of something, if expand 1 of things later, shows contents when expanded it, not when logged it. response.key5 empty when logged it, had things added it, before expanded in console.

this behavior quite squirrelly. instance, on chrome, can matter whether have console open or closed when console.log happens. if have console closed, logs static thing can't expand.

here's simple example demonstrating problem.

in chrome:

  1. make sure console closed.
  2. run snippet.
  3. open console.

you'll see array, , if expand it, you'll see entry added after console.log line.

var = [];  console.log(a);  a.push("hi there");

contrast console.log(json.stringify(...)):

var = [];  console.log(json.stringify(a));  a.push("hi there");

console.dir similar console.log, logs "live" version, if console closed:

var = [];  console.dir(a);  a.push("hi there");

when have console closed, open later, console.dir shows array[1] expansion arrow, shows entry. bizarrely, if have console open, see array[0] — expanding shows entry:

enter image description here

this sort of makes sense, because array empty when logged it, you're seeing contents of when expanded it.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -