p5.js loadStrings() 什么都不做

p5.js loadStrings() is doing nothing

我正在为我的项目使用 p5.js,我必须从另一个文件夹中的文件加载一些数据。

我的js代码写在'js'文件夹里,数据文件在'txt'文件夹里。 'js' 和 'txt' 文件夹都在同一个根目录中。

这是我的代码,

var data;

function preload() {
   data = loadStrings('../txt/data.txt');
   console.log(data);
   console.log(data[0]);
}

这是日志:

0: "abcde"
1: "fghij"
2: "klmno"
length: 3
[[Prototype]]: Array(0)

undefined

请求如下:

Request URL: http://localhost:3000/txt/data.txt
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:3000
Referrer Policy: strict-origin-when-cross-origin

当我打印整个数组时它显示正确的结果,但是当我访问数组的每个数据时,它出错了。我的项目有什么问题?

由于您是在预加载中调用,因此您需要访问设置或绘制函数中的数据。

function setup() {

console.log(data[0])
}

否则,您将需要使用回调函数来处理数据。

function setup() {
 loadStrings('../txt/data.txt', myCallback);
}

function myCallback(data) {
console.log(data[0])
}