簡體   English   中英

如何動態地將新數組添加到現有數組中

[英]How to add new array in to existing array dynamically

我想動態地在現有數組中添加新數組。 在這里,我嘗試將數組添加到共享服務中的現有數組。

這是我的代碼

var shareService = angular.module('ibaDataService', []);
shareService.service('shareData', function () {
    this.comonData = [];
    this.tabData = [];
    this.pushArray = function (arrayName) {
        //this.comonData.push(arrayName[]);
          // here i want to add commonData.newArray[]
 }
    });

使用Array#concat

this.comonData = this.comonData.concat(arrayName);

concat()方法返回一個新數組,該數組由調用它的數組組成,並與作為參數提供的數組和/或值連接。

你需要的值存儲this變量中嵌套內引用它之前function

例如:

var shareService = angular.module('ibaDataService', []);
shareService.service('shareData', function () {
    var self = this;
    this.comonData = {};
    this.tabData = [];
    this.pushArray = function (key, value) {
        // self holds the value of the parent instance
        self.comonData[key] = value;

}});

self現在被用來保持到原來的參考this甚至作為上下文已經改變(另一個函數內)。

使用數組concat

var shareService = angular.module('ibaDataService', []);
shareService.service('shareData', function () {
    this.comonData = [];
    this.tabData = [];
    this.pushArray = function (arrayName) {
        this.comonData = this.comonData.concat(arrayName);
  }
});

你想動態地做,我認為你可以使用“手表”:

$rootScope.$watch('variableToWatch', function() {
       // - Call concat code here
   });

然后,每次更改源數據時都會執行代碼。 當然,您必須為您的服務添加“$ rootScope”依賴項。

您可以使用concat合並數組:

var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
// Result is: Cecilie,Lone,Emil,Tobias,Linus

在你的情況下:

this.comonData.concat(someOtherArray);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM