0

I have a javascript array. The array contains many records. When I loop using the for loop or try to get the length it is showing zero.

console.log("studentAry",this.studentAry); // console showing all the array record

console.log("studentAry",this.studentAry.length) // lenght showing zero

for(var tt=0;tt < this.studentAry.length;tt++){
     console.log("studentAry",this.studentAry[tt]);
 }

enter image description here

vvvvv
  • 25,404
  • 19
  • 49
  • 81
John Ken
  • 898
  • 1
  • 13
  • 26
  • This is an `async` issue, but without seeing the rest of the code it's hard to say how to fix. Basically your console is showing a live view of the array, as can be seen by `[]` at the top.. – Keith May 01 '19 at 10:58
  • console your array you are getting in `studentAry` with `JSON.stringify(this.studentAry)` and paste it here so we can able to check if how the array is generating. – Kirankumar Dafda May 01 '19 at 11:01
  • @KirankumarDafda It will be `[]`. – Keith May 01 '19 at 11:03
  • @Keith may be I am wrong but if we get the array list format we can help him. – Kirankumar Dafda May 01 '19 at 11:08

2 Answers2

1

What your are seeing here is how Chrome debugger works, when you console.log an object chrome keeps a reference to this, if you grab this data asynchronously this can sometimes be confusing.

But there is a hint that this is the issue, if you look at your output you will notice the first line has [], this basically is saying at the point you console logged, the array was empty, but if you then click on it, Chrome will re-evaluate that reference, and at that point your array is now showing the values.

Below is a really simple snippet showing this. I basically fill two arrays called a & b, but I fill a asynchronously.

If you look in the console log you will see.

a.length = 0
>[]
b.length = 3
>(3) [1, 2, 3]

But if you now click on the [], magically you see values.

const a = [];
setTimeout(() => {
  a.push(1,2,3);
}, 1);

console.log(`a.length = ${a.length}`);
console.log(a);

const b = [];
b.push(1,2,3);

console.log(`b.length = ${b.length}`);
console.log(b);
<p>Look in Chrome console,</p>

<p>Expand the first array, you will see [1,2,3],  even though here it's showing []</p>
Keith
  • 22,005
  • 2
  • 27
  • 44
  • Nothing will be gc'ed here. – Jonas Wilms May 01 '19 at 11:54
  • @JonasWilms You know I'm sure I'd left the console open for a long while, and when I tried to click and expand later nothing happened, I thought it might have been using a timed WeakRef or something. But it might have just been a miss click on my behalf, I'll remove that comment as I can't seem to make it happen again. – Keith May 01 '19 at 12:57
-1

I don't what is your array. can you try

[...this.studentAry].length 
Gabriel Tong
  • 206
  • 3
  • 12