JavaScript数组长度返回0

问题描述 投票:0回答:1

[当我使用console.log打印数组长度时,它返回0。但是在控制台中,如果我写txt.length,它将返回实际长度(在我的情况下为60)。因此,我无法遍历txt数组。

var txt;

function preload() {
  txt = loadStrings("DataProcess/outData.txt");
  console.log(txt);
  console.log(txt.length);
}
javascript arrays
1个回答
1
投票

您需要在回调中获取长度。从文档中,该函数接受3个参数

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

意味着您应该执行以下操作:

var txt;

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

}
© www.soinside.com 2019 - 2024. All rights reserved.