繁体   English   中英

初始化包含数组的JavaScript对象

[英]Initializing a javascript object containing an array

我有以下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]);

为什么? 我是Java语言的新手,但我读到的东西很少,建议应该没问题。 显然不是。 了解我所缺少的东西会有所帮助。 谢谢。

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

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]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM