Multidimensional Array Object allocation

So far, I'm trying to create a 2-Dimensional JSON array to hold a series of shapes inside a series of 'frames'. So far I thought I had it, but I can only push shapes to frame[0]; as soon as I pass it frame[1] I get the error Uncaught TypeError: Cannot read property 'shape' of undefined.

Why can't my browser recognise frame[1] as a potential next storage area for the frame array? Is it something to do with how I've initialised the JSON Array?

Relevant code so far:

function Obj(type, x, y, w, h, r) { "use strict"; this.type = type || null; //rect, crcl, line, text this.x = x || null; this.y = y || null; this.w = w || null; //used for rect, line this.h = h || null; //used for rect, line this.r = r || null; //used only for crcl } var keyframes = { 'frame': [{ 'shape': [] }] }; var shape1 = new Obj('rect', 20, 20, 20, 20, 0); var shape2 = new Obj('crcl', 20, 20, 0, 0, 20); keyframes.frame[0].shape.push(shape1); keyframes.frame[1].shape.push(shape2);

-------------Problems Reply------------

It does recognize frame[1] as a potential place to put something, but you haven't put anything there. Your code expects frame[1] to be a reference to an object but you only initialize the first element that way.

keyframes.frame[1] = { shape: [] };

will initialize the next element. Without that initialization, keyframes.frame[1] is undefined.


Your initialization of keyframes is as follows:

  • an object
  • contains a 1 element array 'frame'
  • 'frame' contains an object

You CANNOT access keyframes.frame[1] because it does not exist (frame is a 1 element array so ONLY keyframes.frame[0] is valid)


  • Create the keyframes.frame[1] element

    • keyframes.frame.push({shape: []}); //now keyframes.frame[1] exists
  • push shape 2 to the object added above as you attempted before

    • keyframes.frame[1].shape.push(shape2); //this should now be valid
Category:javascript Views:2 Time:2018-04-14

Related post

Copyright (C), All Rights Reserved.

processed in 0.082 (s). 11 q(s)