gpt4 book ai didi

For循环中数组内的Javascript数组

转载 作者:行者123 更新时间:2023-12-03 10:54:02 25 4
gpt4 key购买 nike

我的 friend 们。我有以下情况。第一个循环效果很好。但第二个似乎无法识别“can[i]”。我只是尝试在第二个数组上使用“{}”,但我认为我做错了。我还需要在将来的“if”语句中调用这些变量。谢谢。

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

最佳答案

您的代码工作正常,但是您正在测试这些值,或者您对应该存储的内容的假设是错误的。 (例如: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);

关于For循环中数组内的Javascript数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28331097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com