Javascript array.length 为零,但数组中有元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42260524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:00:56  来源:igfitidea点击:

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

javascriptarraysscopeelectron

提问by Taira

I'm currently in the process practicing using electron, but I'm quite new with javascript and I've come across a problem which has me completely baffled. I have the following code:

我目前正在练习使用电子,但我对 javascript 很陌生,我遇到了一个让我完全困惑的问题。我有以下代码:

    function getPaths() {
      var dirPath = document.getElementById("mdir").innerHTML;
      var filePaths = [];
      fs.readdir(dirPath, function(err, dir) {
        for(var i = 0, l = dir.length; i < l; i++) {
          var filePath = dir[i];
          filePaths.push(dirPath + "/" + filePath);
        }
      });
      console.log(filePaths);
      console.log(filePaths.length);
    }

Which is supposed to look into a directory defined by dirPath, then it loops through and obtains the full path of all files in that directory. It appends them to an array, and then at the bottom, it logs the array to the console, followed by the length of the array. What is baffling me is that given that code, the array logs to the console like expected, but then the console logs zero as the length. My current thinking is that it's got something to do with scope, but that doesn't make sense because I'm declaring the array, filePathsin the function above the one that's running. Unless I've missed something. Could anyone point out what I'm doing wrong?

它应该查看由 定义的目录dirPath,然后循环遍历并获取该目录中所有文件的完整路径。它将它们附加到一个数组,然后在底部,它将数组记录到控制台,然后是数组的长度。令我困惑的是,给定该代码,数组按预期记录到控制台,但随后控制台将长度记录为零。我目前的想法是它与作用域有关,但这没有意义,因为我在filePaths正在运行的函数上方的函数中声明了数组。除非我错过了什么。谁能指出我做错了什么?

回答by ibrahim mahrir

readdiris asynchronous. It won't get the result right away. You should log the filePathsinside the callback. The only reason why the console show the value is because the console evaluate the array when you unfold it.

readdir是异步的。不会马上得到结果。您应该记录filePaths回调内部。控制台显示该值的唯一原因是控制台在您展开数组时对其进行评估。

When you press the little arrow on the left, put the mouse on the ibox on the right. What happen is that the console keeps a reference to the array, so when the user unfold the array it then show what its current value is. But when you log filePaths.lengththe array is empty because readdirdidn't finish reading yet that's why you get 0. But by the time you open the console and press that arrow, readdirwill already be done reading and the console will print the current value of the array (after it been filled).

当你按下左边的小箭头时,把鼠标放在i右边的盒子上。发生的情况是控制台保留对数组的引用,因此当用户展开数组时,它会显示其当前值。但是当你记录filePaths.length数组是空的,因为还readdir没有完成读取,这就是为什么你得到 0。但是当你打开控制台并按下那个箭头时,readdir已经完成读取并且控制台将打印数组的当前值(填满后)。

enter image description here

在此处输入图片说明

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

演示问题的示例:(不是解决方案,只是为了了解真正发生的事情)

Try and run this code and see what happen:

尝试运行此代码,看看会发生什么:

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 0and a string array[]. Now because arrays could have tons of data, the console won't show that data untill the user unfold the array. So what the console does is keep a reference to the array untill the user press unfold arrow. If you unfold the array before 5 seconds you see that the array is empty (not filled yet). If you wait untill the 5 seconds pass then unfold it, then you'll see that it's filled.

这里数组及其长度都在数组填充之前记录。数组将在 5 秒后填充。所以输出将是0一个字符串array[]。现在因为数组可能有大量数据,所以在用户展开数组之前,控制台不会显示这些数据。所以控制台所做的是保持对数组的引用,直到用户按下展开箭头。如果在 5 秒之前展开数组,您会看到数组是空的(尚未填充)。如果您等到 5 秒钟过去后再展开它,那么您会看到它已被填满。

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 confusingsometimes.

注意:此外,记录到控制台的行(类似于> Array(0))只是日志发生时对象/数组的字符串表示。如果对象/数组发生变化,它就不会更新。所以有时这也可能看起来令人困惑

I hope it's clear now.

我希望现在清楚了。

回答by Jeremy Hymanson

Just to expand on @ibrahim-mahrir 's answer, they means like this

只是为了扩展@ibrahim-mahrir 的回答,他们的意思是这样的

function getPaths() {
    var dirPath = document.getElementById("mdir").innerHTML;
    var filePaths = [];
    fs.readdir(dirPath, function(err, dir) {
        for (var i = 0, l = dir.length; i < l; i++) {
            var filePath = dir[i];
            filePaths.push(dirPath + "/" + filePath);
        }
        console.log(filePaths);
        console.log(filePaths.length);
    });
}