在Angular 4中将数据插入具有特定索引的数组中

时间:2018-06-18 15:29:33

标签: arrays angular typescript

为什么这不适用于TypeScript?

示例:

views: any[] = [360001232825, 360001232845, 360001217389];
MyArray:any[];

     for (var i = 0; i < this.views.length; i++) {
            this.subscription = this.dataService.getMyData(this.views[i]).subscribe(data => {
                this.myArray[this.views[i]]=data;
            });
        }

当我使用.push时,数据被插入到我的数组中,但我想使用特定的索引。

1 个答案:

答案 0 :(得分:0)

如果要插入Item use splice。但显然你想使用Map或对象。

&#13;
&#13;
let ar = ["one", "two", "four", "five"];

console.log("Before:\n" + ar);
ar.splice(2, 0, "three");
console.log("After:\n" + ar);
&#13;
&#13;
&#13;

也许这会有所帮助:

&#13;
&#13;
let namedIndexes = [1564789, 234895, 249846];
let map = {}; 

let data = "this is your data arg";

namedIndexes.forEach((v, i, ar) => {
  map[v] = data + " data at " + v;
});

console.log(map);
&#13;
&#13;
&#13;

&#39;映射&#39;就像你的this.myArray,&#39;数据&#39;是你的参数和'namedIndexes&#39;是你的视图数组。我希望代码解释自己。