未捕获的引用错误,“...”未定义

Uncaught reference error, "..." is not defined

我正在尝试从 5 个不同的网站加载 3 个字符并将它们连接成一个字符串,即使我使用的是 try & catch 语句字符串说“未捕获的引用错误”和任何带有数字的代码导致一个'unexpected tokens error'。我目前正在使用 P5.js 框架,但愿意尝试普通的 .js。

谢谢

我的代码:

var data;
function setup(){

    var url = [];

    url[0] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'
    url[1] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'
    url[2] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'
    url[3] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'
    url[4] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'

    try{
        for (let i = 0; i < 5; i++){
            data += loadJSON(url[i], gotData, 'jsonp') + ' '
        }
    } catch (data){
        console.log('oh well');
    }

}

function draw(){
    createCanvas(400,400);
    background(225);
    text(data, 0, 200);
}

function gotData(data){
    text(data, 100, 200);
}

来自the P5.js reference

Loads a JSON file from a file or a URL, and returns an Object. Note that even if the JSON file contains an Array, an Object will be returned with index numbers as keys.

This method is asynchronous, meaning it may not finish before the next line in your sketch is executed.

最后一行解释了发生了什么:loadJSON() 函数是异步的,这意味着它不直接 return 任何东西。所以像这样的行没有意义:

data += loadJSON(url[i], gotData, 'jsonp') + ' '

请查看参考中的示例以了解如何正确使用 loadJSON() 函数,但基本上您要么需要使用回调函数,要么需要使用 preload() 函数。