Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

javascript - array.length is zero, but the array has elements in it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

readdir is asynchronous. It won't get the results right away. You should use the filePaths inside the callback. The only reason why the console shows the value is because the console evaluates the array when you unfold it.

When you press the little arrow on the left, put the mouse on the i box on the right. What happens is that the console keeps a reference to the array, so when the user unfolds the array it then shows the current value of the array. But when you log filePaths.length the array is empty because readdir didn't finish reading yet, that's why you get 0. But by the time you open the console and press that arrow, readdir will have already done reading and the console will print the current value of the array (after it's been filled).

enter image description here

Example to demonstrate the problem: (not a solution, it's just to understand what is really happening)

Open the browser console and try this code and see what happens:

var arr = [];

setTimeout(function() {
  arr.push(1, 2, 3);
}, 5000);

console.log(arr.length);

console.log(arr);

Here the array and it's length are both logged before the array is filled. The array will be filled after 5 seconds. So the output will be 0 and a string representation of the array array[]. Now because arrays could have tons of data, the console won't show that data until the user unfolds the array. So what the console does is keep a reference to the array until the user press the unfold arrow. If you unfold the array before 5 seconds you'll see that the array is empty (not filled yet). If you wait until the 5 seconds pass then unfold it, then you'll see that it's filled, even though it was logged as an empty array.

Note: Also, the line that get logged to the console (something like > Array(0)) is just a string representation of the object/array at the moment the log happens. It won't get updated if the object/array changes. So that also may seem confusing sometimes.

I hope it's clear now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...