gpt4 book ai didi

javascript - 在另一个数组中使用 array.push 会产生 undefined

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

我在尝试在 Fire 数组中定义数组时遇到了问题(见代码)。

我使用 console.log() 来输出我的 Fire[] 数组中的数组长度(作为调试),但收到一条错误消息,指出该数组未定义。这是我的代码:

var Fire = [];

var fire = function FireGen()
{
this.particle = [];
var part = function Particle()
{
};
this.particle.push(part);
};
Fire.push(fire);

console.log(Fire.particle.length); //Outputs undefined

在 JavaScript 中使用对象和数组时,我还是个新手。如果有人能解释为什么我的数组未定义,我将不胜感激。

最佳答案

正如其他人所指出的,Fire 是一个数组,因此要访问该数组中第一个元素的属性,您需要使用 Fire[0]...。但是,您的代码还有一些其他问题也需要修复。

您的 FireGenParticle 函数似乎被定义为构造函数(您在函数体中使用了 this)。所以你应该用 new 调用这些函数运营商,例如新的 FireGen()。进行此更改后,您可能应该重新安排代码,以便将 xy 作为参数传入,并且每个函数只定义一次。

例如:

var Fire = [];
function FireGen(x, y)
{
this.x = x;
this.y = y;
this.particle = [];
this.particle.push(new Particle(x, y));
};
function Particle(x, y)
{
this.x = x;
this.y = y;
};

function spawnFire(event)
{
var x = event.clientX;
var y = event.clientY;
Fire.push(new FireGen(x, y));

console.log(Fire[0].particle.length); //Outputs undefined
}

document.addEventListener('click', spawnFire);

关于javascript - 在另一个数组中使用 array.push 会产生 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54355332/

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