[英]How to access elements inside an array of objects in Javascript for a movieapp prototype
[英]How to push objects into array inside of a JavaScript Prototype?
我有一個Angular Factory,其工作是保存特殊對象並在以后檢索它們。
(用於在切換視圖時保存用戶工作流程)。
基本上我需要保存帶有名稱的對象以及一組標簽。 我的問題是將標簽保存到數組部分。
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
};
}]);
在不同的控制器中,我現在將一些數據保存到TagFactory內的new Prototype
中:
TagFactory.saveTags('TEST', tagObj);
現在回到我的工廠,在那里你可以看到console.log(nameTagContainers);
以下是日志:
[TagsObject]
0: TagsObject
tags: 1
name: "TEST"
__proto__: TagsObject
length: 1
__proto__: Array[0]
^標簽是一個數組,但它顯示1,而不是對象詳細信息...你看到我哪里出錯了嗎?
更新: KauêGimenes在下面回答了這個問題,但我正在分享我為解決其他問題而添加的額外代碼。
每當為當前選擇的名稱選擇新標簽時,它就會生成一個新的Prototype,而不是將標簽保存到現有的Prototype中:
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);
};
試試這種方法:
// 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 ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.