简体   繁体   中英

Creating a P5.js 2-Dimensional Array

I'm trying to port my working processing sketch to p5.js so I can use it online. But I'm running into a problem when trying to set the values in a 2 dimensional array. I think I'm following the correct syntax shown in the 2d array section of the API, but am getting an uncaught type error that says "cannot set property 0 of undefined".

The sketch is pretty simple, I'm just trying to read from a CSV and store the data in a 2D array:

var cols = 8;
var rows = 8;
var month = 1;
var values = [];
var table;

function preload(){
    table = loadTable("1988.csv", "csv");
}

function setup() {
    createCanvas(800, 800);
    var totalRows = table.getRowCount();

    for (var m = 0; m < 12; m++) {
        for (var c = 0; c < cols; c++) {
            values[c]=[];
            for (var r = 0; r < rows; r++) {
                values[r+m*rows][c] = table.getNum(m*rows*cols + c*rows + r, 0);
            }
        }
    }
}

Any help is very much appreciated!

Thank you for your time.

Try allocating the array before setting array access values to undefined objects:

var cols = 8;
var rows = 8;
var month = 1;
var months = 12;
var values = new Array(months);
var table;

function preload(){
    table = loadTable("1988.csv", "csv");
    for(var i = 0 ; i < months; i++) values[i] = [];//initialize 2nd dimension of the array as well, not just the 1st
}

function setup() {
    createCanvas(800, 800);
    var totalRows = table.getRowCount();

    for (var m = 0; m < 12; m++) {
        for (var c = 0; c < cols; c++) {
            values[c]=[];
            for (var r = 0; r < rows; r++) {
                values[r+m*rows][c] = table.getNum(m*rows*cols + c*rows + r, 0);
            }
        }
    }
}

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