繁体   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