5

我有一個角工廠,他的工作是保存特殊對象並在稍後檢索它們。
(用於在切換視圖時保存用戶工作流程)。如何將對象推入JavaScript Prototype中的數組?

基本上我需要保存具有名稱的對象,以及一組標籤。我的問題是將標籤保存到數組部分。

原型構造:

// define the TagsObject constructor function 
var TagsObject = function(name, tag) { 
    this.name = name; 
    this.tags = [].push(tag); 
    return this; 
}; 

全面的工廠代碼:

.factory('TagFactory', [function() { 

    // Init TagFactory: 
    var tagContainers = []; 

    // define the TagsObject constructor function 
    var TagsObject = function(name, tag) { 
     this.name = name; 
     this.tags = [].push(tag); 
     return this; 
    }; 

    console.log('tagFactory'); 
    console.log(TagsObject); 

    var saveTags = function(name, tag) { 

     tagContainers.push(new TagsObject(name, tag)); 

     console.log('saveTags:'); 
     console.log(tagContainers); 
    }; 

    var getTags = function(name) { 
     console.log(name); 
     return this; 
    }; 

    return { 
     saveTags : saveTags, 
     getTags : getTags 
    }; 
}]); 

在不同的控制器我現在有些數據保存到new Prototype的TagFactory內:

TagFactory.saveTags('TEST', tagObj); 

現在回到我的工廠,在那裏你看到console.log(nameTagContainers);以下是日誌:

[TagsObject] 
    0: TagsObject 
    tags: 1 
    name: "TEST" 
    __proto__: TagsObject 
    length: 1 
    __proto__: Array[0] 

^標籤是一個數組,但它顯示1,而不是對象的細節......你看到我錯在哪裏?



UPDATE:對此問題予以Kauê Gimenes下面回答,但是我分享我加入到解決我的問題,其他額外的代碼。

這是每一個被選定爲當前選擇的名稱的新標籤時,它產生一個新的原型,而不是保存標籤到現有的原型:

var saveTags = function(name, tag) { 

    console.log(tagContainers.length); 

    if (tagContainers.length != 0) { 
     for(var i = 0; i < tagContainers.length; i++) { 
      if (tagContainers[i].name == name) { 
       console.log('Found existing name! Add tag to existing obj'); 
       tagContainers[i].tags.push(tag); 
       break; 
      } else { 
       console.log('New name, create new obj'); 
       tagContainers.push(new TagsObject(name, tag)); 
      } 
     } 
    } 
    else { 
     console.log('New name, init: create the first obj'); 
     tagContainers.push(new TagsObject(name, tag)); 
    } 

    console.log(' '); 
    console.log('tagContainers:'); 
    console.log(tagContainers); 
}; 

回答

2

試試這個辦法:

// define the TagsObject constructor function 
var TagsObject = function(name, tag) { 
    this.name = name; 
    this.tags = [tag]; 
    return this; 
}; 

的最佳方式初始化的陣列以包括括號內的元素

[ 1 , 2 , 3 ] 

但是如果你想用n初始化元素,你可以使用concat函數。

[ 1 ].concat([ 2 , 3 , 4 ]) 

其結果將是:

[ 1 , 2 , 3 , 4 ] 
+0

啊是啊,做工作,做回答這個問題......不過,我才意識到我寫了這個代碼錯誤。有幾個標籤可供用戶選擇1個名稱。現在我的代碼每次用戶只需爲一個名稱點擊一個新標籤就會創建一個新的Prototype。謝謝!我需要更新我的代碼,並可能發佈一個新問題。 –

+1

我包含一些額外的信息,使答案更清楚,如果您仍然有任何問題可以隨意問! –

+0

啊好,所以* n *元素陣列可以在這裏修復我的新問題 –