javascript - 如何在对象中正确声明对象的 Javascript 数组

标签 javascript arrays object declaration

我正在尝试创建一个包含对象数组的对象。我使用 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/

相关文章:

c++ - 数组作为模板参数 : stack or heap?

Ruby/Watir - 从数组格式化打印

php - 如何在 PHP Heredoc 语法中显示数组元素或对象属性的值

ios - 自定义 uicollectionview - 传递数据

javascript - 向第三方 jquery 插件添加动画过渡 - Dropit

javascript - 错误: Permission denied to access property "getComputedStyle"

javascript - 检测移动设备并更改 HTML

javascript - 如果没有连接,XHR 返回什么?

asp.net-mvc - 如何在强类型 View 中包含多个模型对象?

python - 将带有坐标的一维数组转换为numpy中的二维数组