gpt4 book ai didi

javascript 数组长度未显示在我的控制台日志中

转载 作者:行者123 更新时间:2023-11-30 13:08:17 25 4
gpt4 key购买 nike

我正在开发一个 HTML5 canvas 游戏,我有一组图像被绘制到 Canvas 上。来自数组的图像目前都被正确绘制,我有一个 console.log 行,我想用它在控制台中显示数组的大小。但是由于某种原因,控制台一直告诉我数组长度未定义。

我用来打印数组长度的行是:

console.log("sources array length = " + sources.length);

它在一个for循环中:

        for (index=0;index < numImages ;index++){
console.log(index);
images[index] = new Image();
images[index].src = sources[index];
console.log("Adding " + sources[index]);
callback(images[index]);
console.log("sources array length = " + sources.length);
}

如您所见,我在循环中还有另一个 console.log 语句,用于在每次循环运行时记录...

console.log(index); 

此行在每次循环运行时打印变量索引的值,从 0 开始,每次递增 1,直到达到等于变量“numImages”的值时循环结束。

但是,由于某种原因,每次循环运行时本应打印数组长度的行显示的是“sources array length = undefined”,而不是数组的实际长度。

谁能告诉我这是为什么?如何让它在每次循环运行时显示源数组的长度?

编辑 13/02/2013 @ 15:10

sources 数组在同一文件中定义,使用以下行:

var sources = {};

我没有为数组定义固定长度的原因是因为我需要它的长度是动态的。然后我使用如下行将元素添加到数组中:

sources[0] = document.getElementById("building").src,
sources[1] = document.getElementById("chair").src,
sources[2] = document.getElementById("drink").src,
sources[3] = document.getElementById("food").src,

所以我想让我的 console.log 行做的是告诉我当前数组的长度,即添加了多少元素。正如您在我的原始帖子中的第一段代码中看到的那样,我有一个 console.log,它会在每次将元素添加到源数组时向控制台打印一条消息 - 它们显然已正确添加,否则,它们不会显示在 Canvas 上...因此数组必须有一个长度,该长度是在图像绘制到 Canvas 上时定义的,否则它们不会在要绘制的数组中。

最佳答案

But, for some reason, the line that should be printing the array length is displaying "sources array length = undefined" each time the loop runs, and not the actual length of the array.

...这告诉我们 sources 没有 length 属性,因此不是数组。完全有可能构建一些不是数组但仍然具有名称为 01 等的属性。例如:

var sources = {0: "zero", 1: "one", 2: "two"};
console.log(sources[0]); // "zero"
console.log(sources.length); // "undefined"

如果您通过输出一些服务器端信息来获取 sources,它很可能会以上面的形式输出(带有数字属性名称的普通对象,可能会在引号中)而不是作为一个实际的数组,它看起来像这样:

var sources = ["zero", "one", "two"];

重新编辑

The sources array is defined in the same file, using the line:

var sources = {};

The reason I have not defined a set length for the array, is because I need its length to by dynamic. I have then added elements to the array using lines like this:

sources[0] = document.getElementById("building").src,
sources[1] = document.getElementById("chair").src,
sources[2] = document.getElementById("drink").src,
sources[3] = document.getElementById("food").src,

这不是问题,JavaScript 数组是动态的(事实上,它们是 not really arrays at all — 或者至少,标准类型不是,有更新类型的实际上是数组)。所以只要改变

var sources = {};

var sources = [];

使它成为一个数组。然后你可以按照你已经在做的方式添加到数组中(这绝对没问题)或者你可以使用sources.push(document.getElementById("chair").src); 等等。

关于javascript 数组长度未显示在我的控制台日志中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14856208/

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