打字稿 - 从数组中获取最后一个元素

时间:2018-04-07 21:09:34

标签: typescript

我试图从数组中提取所有元素,但我却得到了它的最后一个元素
这是我的代码:

// this.data contains data from a http.get
// I tried using user: [] and user: any = [];  
user: Array; // 
pass: Array;
for (const x of this.data) {
                this.user = x.username;
                this.pass = x.password;
           } // console.log(this.user); Output = lastelementfromthearray

2 个答案:

答案 0 :(得分:1)

如果你需要从另一个数组中包含的对象中获得一些字段的数组,那就是:

this.user = this.data.map(({ username }) => username);
this.pass = this.data.map(({ password }) => password);

如果阵列足够大或地点对性能至关重要,可以在一个循环中完成,最好是for / while

this.user = [];
this.pass = [];

for (let i = 0; i < this.data.length; i++) {
  this.user.push(this.data[i].username);
  this.pass.push(this.data[i].password);
}

答案 1 :(得分:0)

现在,您在每次迭代时都会覆盖this.user。由于this.user是一个数组,因此您要做的是将x.username推送到数组。同样适用于其他阵列。

    user = [];
    pass = [];
    for (const x of this.data) {
      this.user.push(x.username);
      this.pass.push(x.password);
    }
相关问题