简体   繁体   English

初始化包含数组的JavaScript对象

[英]Initializing a javascript object containing an array

I have the following C++ struct which I want to create as faithfully as possible in Javascript: 我有以下C ++结构,希望在Javascript中尽可能忠实地创建:

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

So I did the following: 所以我做了以下事情:

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

Now, the following works to create a Vertex instance: 现在,以下工作可创建一个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];

but the following (slicker?) doesn't: 但是以下内容(闪烁吗?)没有:

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

Why? 为什么? I am new to Javascript and what little I have read suggests it should be ok. 我是Java语言的新手,但我读到的东西很少,建议应该没问题。 Obviously not. 显然不是。 It would be helpful to understand what I am missing. 了解我所缺少的东西会有所帮助。 Thanks. 谢谢。

you need to use the arguments passed in to the function for it to work, as: 您需要使用传递给函数的参数才能使其正常工作,如下所示:

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

You're constructor should initialize the properties: 您是构造函数,应初始化属性:

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