javascript - "TypeError: can't convert undefined to object" when Dynamically Resizing 2D Array -
i read text, consisting of triads of comma separated numbers 1 triad per line, 2d array. not know in advance array dimensions be. use following code.
// read data matrix var inputdata = [[]]; while (alltextlines.length>0) { datarecord=alltextlines.shift(); entries = datarecord.split(','); var xcoord=parseint(entries.shift()); var ycoord=parseint(entries.shift()); var zcoord=parseint(entries.shift()); if (ycoord>=inputdata.length) inputdata[ycoord]=[]; inputdata[ycoord][xcoord]=zcoord; }
this results in
typeerror: can't convert undefined object
from firebug when try call
if (ycoord>=inputdata.length) inputdata[ycoord]=[];
or
inputdata[ycoord][xcoord]=zcoord;
i thought javascript arrays dynamically resized assigning value index higher current size.
they can dynamically resized when exist. there's no such thing 2d array in javascript. create in initialization 1d array array in first element.
all have check first dimension before adding in second dimension. you're doing now, it's minor change:
if (inputdata[ycoord] == null) inputdata[yucoord] = [];
you have instead of checking length because, if "ycoord" 3, positions 0, 1, , 2 still null after initialize position 3. subsequently, "ycoord" value of 2 fail length check, slot empty nevertheless.
alternatively, this:
for (var yplus = inputdata.length; yplus <= ycoord; inputdata[yplus++] = []);
Comments
Post a Comment