我正在尝试创建一个包含对象数组的对象。我使用 jquery 选择器来确定数组中所需的对象数量。我在这里遇到了一些问题,因为当我进入 for 循环时,Firefox 说 “this.obj 未定义” 我尝试了 this.obj = new Array()> 语法以及 this.obj[ ]; 语法。
function Base() {
this.n = document.querySelectorAll('transform').length /3;
this.obj = new Array(n); //array declaration
for (var i = 0; i < this.n; i++) {
this.obj[i] = new x3dSphere("b"+i);
}
}
我只看到过像 this.obj = [1,2,2,4] 或 JSON 形式 obj: [1 那样声明的对象内的数组示例,2,3,4]。我确信这确实很容易做到,但我似乎无法在任何地方找到示例。
最佳答案
以下内容对我有用:
function Base() {
this.n = 5;
this.obj = [];
for (var i = 0; i < this.n; i++) {
this.obj.push(new Test());
}
}
测试
所在位置:
var Test = function () {};
看起来真正的问题是它从未创建 this.obj
因为 n
未定义。如果您想像以前一样声明数组,请尝试 new Array(this.n)
。
编辑
Would new Array(this.n) be faster than the this.obj=[] syntax since it's pre-allocated?
有趣的是,the answer is no 。
此外,这个问题的公认答案对 JavaScript 数组性能的许多其他方面进行了很好的讨论:What is the performance of Objects/Arrays in JavaScript? (specifically for Google V8)
我已经更新了我的答案以使用 Array.push()
因为它显然比 Array[i] = new Obj()
快得多(向 Jason 大声喊叫,他在最初的答案中使用了它)。
关于javascript - 如何在对象中正确声明对象的 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690449/