gpt4 book ai didi

javascript - 在 JavaScript 中创建其他对象的数组?

转载 作者:行者123 更新时间:2023-12-02 20:46:17 25 4
gpt4 key购买 nike

这样的事情可能吗:

function FooClass()
{
var barsArray=new Array();
var index=0;

function addBar()
{
barsArray[index]=new BarClass(index);
}
}

function BarClass()
{
var myIndex;
function BarClass(index)
{
myIndex=index;
}
}

最佳答案

我推断您想要一个 Foo 对象,并且该 Foo 对象应该包含一个 Bar 对象数组。每个 Bar 对象都应该知道其父 Foo 对象中的数组索引。

如果这是准确的描述,请尝试以下操作:

function BarClass(idx) {
this.myIndex = idx;
}

function FooClass(howMany) {
this.barsArray = [];

for (var x = 0; x < howMany; x++) {
this.barsArray[x] = new BarClass(x);
}

}

var foo = new FooClass(5);
// foo.barsArray[0].myIndex === 0
// foo.barsArray[1].myIndex === 1
// foo.barsArray[2].myIndex === 2
// foo.barsArray[3].myIndex === 3
// foo.barsArray[4].myIndex === 4
// foo.constructor === 'FooClass'
// foo.barsArray[0].constructor === 'BarClass'

祝你好运!

关于javascript - 在 JavaScript 中创建其他对象的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114141/

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