For循环中的数组内部的数组

时间:2015-02-04 20:46:13

标签: javascript arrays

我的朋友们。我有以下情况。第一个循环非常有效。但第二种观点是不能重新认识"可以[i]"。我只是尝试使用" {}"在第二个阵列上,但我认为我做错了。我将来还需要调用这些变量"如果"声明。谢谢。

        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');
    }

2 个答案:

答案 0 :(得分:1)

您的代码可以正常运行,但是您正在测试值或您对应该存储的内容的假设是错误的。 (例如:http://jsbin.com/tanesicoti/1/edit?js,console)。

但它的功效非常低效。在单个循环中编写它的更好方法,而不必在之后搜索DOM就像这样(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);

答案 1 :(得分:0)

您的函数document.getElementById可能无法找到指定的id并返回null。请检查您是否拥有id="canvas0"id="canvas255"的所有元素。

同样重要的是,他们没有和前缀(例如id="canvas001"将找不到,但id="canvas1"将会是