2014-11-01 29 views
0

我正在玩chart.js(http://www.chartjs.org)。目前我有一個基於下面的對象的線圖。在下面的例子中,從存儲爲'x'的數組中填充X軸數據。我有兩個數據集,它們是我的圖表上顯示的兩條線。在下面的例子中,Y軸數據存儲爲'y'和'z'。對象和數組:參照第二個對象更改對象屬性(chart.js示例)

我想添加一些功能,用戶只能顯示一個特定的行或兩者,如果他們想。

換句話說,在數據集屬性中添加或刪除對象實例。

我對以下結構的理解:整件事是一個名爲data的對象;這有兩個屬性稱爲標籤和數據集。 datasets屬性是對象實例的數組。這是一個有效的思考方式嗎?

var data = { 

    labels : x, 
    datasets : [ 
     { 
      fillColor : "rgba(222,223,179,0)", 
      strokeColor : "rgba(222,223,179,1)", 
      pointColor : "rgba(222,223,179,1)", 
      pointStrokeColor : "#fff", 
      data : y 
     }, 

     { 

      fillColor : "rgba(194,95,207,0)", 
      strokeColor : "rgba(194,95,207,1)", 
      pointColor : "rgba(194,95,207,1)", 
      pointStrokeColor : "#fff", 
      data : z 
     }, 

    ] 
} 

我試圖通過創建一個dataSetReference對象像下面解決我的問題:

dataSetReference = [ 
    { 
     fillColor : "rgba(222,223,179,0)", 
     strokeColor : "rgba(222,223,179,1)", 
     pointColor : "rgba(222,223,179,1)", 
     pointStrokeColor : "#fff", 
     data : y 
    }, 

    { 

     fillColor : "rgba(194,95,207,0)", 
     strokeColor : "rgba(194,95,207,1)", 
     pointColor : "rgba(194,95,207,1)", 
     pointStrokeColor : "#fff", 
     data : z 
    }, 

] 

然後引用它在我的原始數據對象像

datasets: dataSetReference[0,1] 

或者只是:

datasets: dataSetReference[0] 

T他沒有工作。任何建議爲什麼不呢?

回答

0

你應該知道,非原始類型對象陣列他們的標準操作讓我們來簡單的例子來說明這一點:

var a = [1,2,3]; 
var b = a; // now b point to the same reference as the a does,meaning any modification to b will be applied to a also 

// for example 
b.push(4); 
console.log(a); // you will get [1, 2, 3, 4] instead of [1, 2, 3] that we are expecting 

//so you can use only : 
datasets: dataSetReference 


//and if you want to access separate items from dataSetReference you can use .slice() method 

    var tmpvar = dataSetReference.slice(0,3,4) // now tmpvar = dataSetReference[0,3,4] 
+0

感謝。任何有關如何在數據集屬性中完整選擇數組元素然後引用特定項的建議?在我的實際項目中,有8個數據集,因此不想列出所有不同組合的單獨對象。 – DVCITIS 2014-11-01 19:10:11

+0

你不想在dataSetReference變量中存儲8個數據集(對象數組)嗎? – Ismail 2014-11-01 19:31:47

+0

我在想如果我在需要的時候只能參​​考其中的一個或兩個,那將是一個體面的方法;你上面的例子表明這是不可能的。現在它看起來像我需要一個由8個對象組成的數組,一個由兩個對象組成的數組,一個由三個對象組成的數組等等,並且當需要只有一行時需要單獨的對象。許多代碼行。 – DVCITIS 2014-11-01 19:34:38

相關問題