初始化包含数组的javascript对象

Initializing a javascript object containing an array

本文关键字:javascript 对象 数组 包含 初始化      更新时间:2023-09-26

我有以下C++结构,我想在Javascript中尽可能忠实地创建它:

struct Vertex
{
   float coords[4];
   float colors[4];
};

所以我做了以下事情:

function Vertex(coords, colors)
{
   this.coords = [];
   this.colors = [];
}

现在,以下操作可以创建一个Vertex实例:

var oneVertex = new Vertex();
oneVertex.coords = [20.0, 20.0, 0.0, 1.0];
oneVertex.colors = [0.0, 0.0, 0.0, 1.0];

但以下(切片机?)没有:

var oneVertex = new Vertex([20.0, 20.0, 0.0, 1.0], 
                            [0.0, 0.0, 0.0, 1.0]);

为什么?我是Javascript的新手,我所读的内容表明它应该还可以。显然不是。了解我缺少的东西会很有帮助。谢谢

您需要使用传递给函数的参数才能使其工作,如:

function Vertex(coords, colors)
{
   this.coords = coords || [];
   this.colors = colors || [];
}

您的构造函数应该初始化属性:

function Vertex(coords, colors)
{
   this.coords = coords;
   this.colors = colors;
}
var oneVertex = new Vertex([20.0, 20.0, 0.0, 1.0], 
                            [0.0, 0.0, 0.0, 1.0]);