簡體   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