无法读取函数中未定义的 属性“0”(p5.js)

Cannot read property '0' of undefined in a function (p5.js)

在我的代码的第一行,我输入了 var array = [] 但我得到指向此函数的错误。如果我在调用函数之前记录数组,那么它应该是什么,但是如果我在函数内部的任何地方这样做,它就不会在错误

之前被记录

let elements = 25
var array = []
let goal = []
let tempAr = []
let i = 1
 
function setup() {
 
    // put setup code here
    createCanvas(600, 600)
    background(25)
    // make the goal array ascending
    while (goal.length < elements) {
        goal.push(i)
        i++
    }
 
    // make the scrambled array
 
    i = 0
    tempAr = goal
    while (i < elements) {
        let rng = Math.floor(random(tempAr.length))
        array.push(tempAr[rng])
        tempAr.splice(rng, 1)
 
        i++
 
    }
 
}
 
function draw() {
    fill('#f1f442')
 
    drawRect()
    sort()
 
}
 
 
function drawRect() {
    i = 1
    while (i <= elements) {
        rect(i * (width / elements) - (width / elements), height - array[i - 1] * height / elements, width / elements, array[i - 1] * height / elements)
        i++
    }
}
 
function sort() {
 
    let sorted = false
 
    while (!sorted) {
 
        sorted = true
        var e = 0
        while (e < array.length) {
 
            if (array[e] > array[e + 1]) {
                let temp = array[e + 1]
                array[e + 1] = array[e]
                array[e] = temp
                sorted = false
 
            }
            drawRect()
            e++
        }
 
    }
 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>

sort() is the name of a built-in function in p5.js.
您必须为您的函数选择不同的名称。因此,将 sort 重命名为其他名称(例如 mysort),使您的代码成为 运行。

let elements = 25
var array = []
let goal = []
let tempAr = []
let i = 1
 
function setup() {
 
    // put setup code here
    createCanvas(600, 600)
    background(25)
    // make the goal array ascending
    while (goal.length < elements) {
        goal.push(i)
        i++
    }
 
    // make the scrambled array
 
    i = 0
    tempAr = goal
    while (i < elements) {
        let rng = Math.floor(random(tempAr.length))
        array.push(tempAr[rng])
        tempAr.splice(rng, 1)
 
        i++
 
    }
 
}
 
function draw() {
    fill('#f1f442')
 
    drawRect()
    mysort()
 
}
 
 
function drawRect() {
    i = 1
    while (i <= elements) {
        rect(i * (width / elements) - (width / elements), height - array[i - 1] * height / elements, width / elements, array[i - 1] * height / elements)
        i++
    }
}
 
function mysort() {
 
    let sorted = false
 
    while (!sorted) {
 
        sorted = true
        var e = 0
        while (e < array.length) {
 
            if (array[e] > array[e + 1]) {
                let temp = array[e + 1]
                array[e + 1] = array[e]
                array[e] = temp
                sorted = false
 
            }
            drawRect()
            e++
        }
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>