简体   繁体   中英

Uncaught reference error, “…” is not defined

I'm trying to load 3 characters from 5 difference websites and a concatenate them into one string, even though I'm using a try & catch statement the strings say'uncaught reference error' and any codes with numbers cause a 'unexpected tokens error'. I'm using the P5.js framework at the moment but willing to try plain .js.

Thanks

My code:

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);
}

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

That last line explains what's going on: the loadJSON() function is asynchronous, which means it doesn't directly return anything. So lines like this don't make sense:

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

Please see the examples in the reference to understand how to use the loadJSON() function correctly, but basically you either need to use a callback function or you need to use the preload() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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