Mario Lima Cavalcanti
Mario Lima Cavalcanti

Reputation: 157

Javascript Array inside Array in For loop

my friends. I have the following situation. The first loop works very well. But the second seens to not recongnize the "can[i]". I just tried to use "{}" on the second Array, but I think I'm doing it wrong. I'll need also to call these variables in future "if" statements. Thank you.

        for (g=0; g<256; g++) {
            document.write('<canvas id="canvas' + g + '" width="8" height="8"></canvas>');
        }

        for (g=0; g<256; g++) {
            document.write('<div id="chr'+g+'"></div>');
        }


    var can = [], ctx = [];
    for (var i=0; i<256; i++){
        can[i] = document.getElementById("canvas" + i);
    }

    for (var i=0; i<256; i++){
        ctx[i] = can[i].getContext('2d');
    }

Upvotes: 0

Views: 72

Answers (2)

George Reith
George Reith

Reputation: 13476

Your code works fine, however you are testing the values or your assumptions about what should be stored is erroneous. (example: http://jsbin.com/tanesicoti/1/edit?js,console).

However it is very inefficient for what it does. A better way to write it in a single loop, and without having to search the DOM afterwards is like so (http://jsbin.com/zozocikanu/2/edit?js,console):

var can = [], ctx = [];

/*
 * Create a node in memory so that we can store the elements inside it
 */
var canvasFragment = document.createDocumentFragment();
var divFragment = document.createDocumentFragment();

/*
 * Initialise our loop variables
 */
var canvasCount = 256;
var canvas;
var div;
for (var i = 0; i < canvasCount; i++) {

  /*
   * Create a canvas element and insert it into its fragment
   */
  canvas = document.createElement('canvas');
  canvas.width = canvas.height = 8;
  canvas.setAttribute('id', 'canvas' + i);
  canvasFragment.appendChild(canvas);

  /*
   * Create a div element and insert it into its fragment
   */
  div = document.createElement('div');
  div.setAttribute('id', 'chr' + i);
  divFragment.appendChild(div);

  /* 
   * Get our array values, objects are passed by reference so
   * even though our elements aren't in the DOM yet, this variable
   * will point to the same item after we do.
   */
  can[i] = canvas;
  ctx[i] = canvas.getContext('2d');
}
/*
 * Insert our items into the DOM. This is much faster as the browser
 * has to repaint when you insert items, but as we insert them in two
 * actions and not 512 (2 * 256) we create 2 repaints and not 512.
 */
document.body.appendChild(canvasFragment);
document.body.appendChild(divFragment);

console.log(ctx[123], ctx.length);

Upvotes: 1

smnbbrv
smnbbrv

Reputation: 24591

Probably your function document.getElementById cannot find specified id and returns null. Please, check if you have all elements from id="canvas0" to id="canvas255".

Also important is that they do not have and prefix (e.g. id="canvas001" will not be found but id="canvas1" will be)

Upvotes: 0

Related Questions