【发布时间】:2023-03-09 22:05:02
【问题描述】:
我一直在用 Javascript 开发一个项目,在某个开发阶段之后,代码停止工作。我已将问题缩小到在 Javascript 中创建和索引“多维”数组。我包含的代码只是为了测试创建数组数组,为数组分配颜色值,然后测试这些值是否可以通过循环遍历“多维数组”的循环显示在屏幕上。
我已经尝试了几乎所有在 Javascript 中创建数组数组的方法——即使在这里也有一些来自答案的代码 sn-ps——但没有任何效果。
function setRGB(image, width1, x1, y1, r, g, b, a) {
var t1 = y1 * width1 * 4 + x1 * 4;
image.data[t1] = r;
image.data[t1 + 1] = g;
image.data[t1 + 2] = b;
image.data[t1 + 3] = a;
}
function draw() {
var pixels = [];
for (var i = 0; i < height; ++i) {
var row = [];
for (var j = 0; j < width; ++j) {
row[j] = 0;
}
pixels[i] = row;
}
var k = 12;
var j = 29;
console.log(pixels[12][29].toString());
var canvas = document.getElementById('test');
var width = 500;
var height = 500;
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
var canvasImage = ctx.getImageData(0, 0, width, height);
var testImage = ctx.createImageData(width, height);
for (var y = 0; y < height; ++y) {
for (var x = 0; x < width; ++x) {
pixels[y][x] = Math.round(Math.random() * 255);
}
}
for (y = 0; y < height; ++y) {
for (x = 0; x < width; ++x) {
console.log(pixels[y][x].toString());
}
}
for (var y = 0; y < height; ++y) {
for (var x = 0; x < width; ++x) {
setRGB(testImage, width, pixels[y][x], pixels[y][x], pixels[y][x], 255);
ctx.putImageData(testImage, 0, 0);
canvasImage = testImage;
ctx.putImageData(canvasImage, 0, 0);
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Array test</title>
</head>
<body onload="draw();">
<canvas id="test">Sorry, but your browser doesn't support the 'canvas' element.</canvas>
</body>
</html>
在 Google Chrome 中,屏幕上不显示任何内容,并且 Web 控制台显示错误:
array-plot-test-1.html:26 Uncaught TypeError: Cannot read property '29' of undefined
at draw (array-plot-test-1.html:26)
at onload (array-plot-test-1.html:60)
即使数组数组在其创建循环中被索引。
第一次在其创建循环之外对数组进行索引时包含测试代码:
var k = 12;
var j = 29;
console.log(pixels[12][29].toString());
在 Mozilla Firefox 中,我收到错误消息:
TypeError: pixels[12] is undefined[Learn More] array-plot-test-1.html:26:3
draw file:///[censored]/[censored]/[censored]/array-plot-test-1.html:26
onload file:///[censored]/[censored]/[censored]/array-plot-test-1.html:1
我至少使用 Stack Overflow 等网站提供的“解决方案”重写了十几次不同的数组测试代码,但到目前为止没有任何效果。我预计我犯了一些基本错误。
奇怪的是,如果我像这样在 Javascript 中创建一个“多维数组”
array1 = [];
for (var i=0; i < max; ++i) {
var temp = [1, 2, 3];
array[i] = temp;
}
使用预定义的数组,然后 Javascript“多维数组”可以正常工作,但我需要任意大小的数组数组,这就是为什么我不能使用上面的代码 sn-p。
【问题讨论】:
-
可能是您的数组中没有
29项吗? -
我的数组的大小无关紧要:当我创建 any 数组数组时,使用任意大小的行和列,然后索引数组,即. a[1][2],产生错误。换句话说,错误似乎并不取决于数组大小。是的,我的数组有 500 行和 500 列,所以我不知道是什么导致了错误。
-
但是您在变量
width和height初始化之前使用它们。请使用let而不是var,以后会避免这些问题。 -
向数组添加数组行时使用
push()方法 -
我尝试将数组创建代码替换为:
var pixels = new Array(height); for (i=0; i < height; ++i) { var a1 = new Array(width); pixels[i] = a1; }
标签: javascript arrays multidimensional-array typeerror undefined-index