简体   繁体   English

Javascript 数组长度返回 0

[英]Javascript array length returning 0

When I am using console.log to print the array length, it returns 0. But in the console, if I write txt.length it returns the actual length (ie 60 in my case).当我使用 console.log 打印数组长度时,它返回 0。但是在控制台中,如果我写txt.length它返回实际长度(在我的情况下为 60)。 For this reason I can't iterate through the txt array.出于这个原因,我无法遍历 txt 数组。

var txt;

function preload() {
  txt = loadStrings("DataProcess/outData.txt");
  console.log(txt);
  console.log(txt.length);
}

You need to get the length in the callback.您需要在回调中获取长度。 from the docs the function accepts 3 arguments从文档 function 接受 3 arguments

loadStrings(filename, [callback], [errorCallback])

meaning you should do something like this:这意味着你应该做这样的事情:

var txt;

function preload() {
  loadStrings("DataProcess/outData.txt", (res) => {
    txt = res
    console.log(txt.length);
  })

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM