P5JS 无法访问对象的值

P5JS Unable to access values of an object

我正在使用 P5.JS 中的 LoadBytes 函数,其中 returns 一个对象,但我无法通过使用“.bytes”或“[[=16] 访问“对象” =]]".

出于某种原因,当 运行 在线服务器时它似乎运行良好。

function get_rom () {
    var fileList = document.getElementById("rom").files;
    var fileReader = new FileReader();
    
    if (fileReader && fileList && fileList.length) {
        url = URL.createObjectURL(fileList[0])
        return loadBytes(url)
    }
}

function loadarom () {
    object = get_rom()
    
    print(object.bytes[1]) // <-- issue here
}

使用 loadBytes() 时,返回的对象不会立即填充 bytes 数组。您需要使用回调参数 loadBytes():

let loadBtn;

function setup() {
    noCanvas();
    noLoop();

    loadBtn = createButton("Load Rom");
    loadBtn.mousePressed(loadarom);
}

function get_rom(onSuccess) {
    let fileList = document.getElementById("rom").files;
    // Alternate method using FileReader has been commented out
    // let fileReader = new FileReader();
    
    /*
    fileReader.addEventListener("load", function () {
    // convert image file to base64 string
    loadBytes(fileReader.result, onSuccess);
  }); */

    if (fileList && fileList.length) {
        loadBytes(URL.createObjectURL(fileList[0]), onSuccess);
        // fileReader.readAsDataURL(fileList[0]);
    }
}

function loadarom() {
    get_rom(obj => {
        print(obj.bytes[0]);
    })
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>
</head>

<body>
    <input id="rom" type="file" />
</body>

</html>

大麦不需要 p5.js 来完成如此简单的任务。
使用 blob.arrayBuffer()

<script type="module">

var file = new File(['abc'], 'abc.txt')
var bytes = new Uint8Array(await file.arrayBuffer())
console.log(bytes)

</script>

(SO! You should support top level await in a async IIFE fn or start adding type="module" to js-code