2016-03-04 30 views
0

我有結構的JavaScript對象上的方法,包括:如何通過在JavaScript中引用來調用變量?

performOperation: function (rel) { 
    var currentArray = []; 

    switch (rel) { 
     case 'templates': 
      currentArray = templates; 
     break; 

     case 'drafts': 
      currentArray = drafts; 
     break; 

     case 'sent': 
      currentArray = sent; 
     break; 

     case 'scheduled': 
      currentArray = scheduled; 
     break; 

     case 'cancelled': 
      currentArray = cancelled; 
     break; 

     case 'inbox': 
      currentArray = inbox; 
     break; 
    } 

    // Series of operations here. 

    switch (rel) { 
     case 'templates': 
      templates = currentArray; 
     break; 

     case 'drafts': 
      drafts = currentArray; 
     break; 

     case 'sent': 
      sent = currentArray; 
     break; 

     case 'scheduled': 
      scheduled = currentArray; 
     break; 

     case 'cancelled': 
      cancelled = currentArray; 
     break; 

     case 'inbox': 
      inbox = currentArray; 
     break; 
    } 
} 

是否有一種方法可以通過參照所述陣列調用此var currentArray使用即或者drafts, inbox, cancelled, ...。在C++和PHP中,我知道我們通過在變量之前使用&來引用。

如果有什麼辦法可以做到這一點在JavaScript中引用,歡迎所有的答案。

+0

JavaScript中沒有引用任何引用。沒門。 – Bergi

+0

如果你正在操作一個對象,比如你的一個數組,你不必寫回來,因爲你從未創建過它的副本。對象是參考值。 – Bergi

+0

你真的想要使用一個對象,並通過動態名稱來引用它的屬性,而不是把一堆不同的變量放在一起。 – Bergi

回答

0

您可以將數據結構更改爲一個對象,該對象具有您所描述的訪問所需的屬性。

var data = { 
     templates: [], 
     drafts: [], 
     sent: [], 
     scheduled: [], 
     cancelled: [], 
     inbox: [] 
    }; 

function performOperation(rel) { 
    var currentArray = data[rel]; 
    // 
    // Series of operations here. 
    // 
    data[rel] = currentArray; 
} 
相關問題