Arrays Typescript-尝试从数组中提取元素。取而代之的是最后一个元素

Arrays Typescript-尝试从数组中提取元素。取而代之的是最后一个元素,arrays,typescript,Arrays,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.pa

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

// 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

现在,在每次迭代中,您都要覆盖
this.user
。由于this.user是一个数组,因此您要做的是将
x.username
推送到数组中。当然,这同样适用于另一个数组

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

如果需要从包含在另一个数组中的对象中获取一些字段的数组,则它是:

this.user = this.data.map(({ username }) => username);
this.pass = this.data.map(({ password }) => password);
如果阵列足够大或位置对性能至关重要,则可以在单个循环中完成,最好是
for
/
,而
:

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);
}
this.user=[];
this.pass=[];
for(设i=0;i
这里有同样的问题:
mc
对象与数组的内容有什么关系?无论如何,除此之外,你的问题是你在每次迭代中都覆盖了
这个.user
,这意味着你只能在循环结束时得到最后一个。@Lior是的,但我不想访问某个,我想访问所有这些。@bugs My bad,我更新了它。那么,在这种情况下,您建议我做什么呢?那么,您已经有了一个数组(数据),包含您需要的所有内容。没有什么可提取的<代码>数据
是您想要的:用户名/密码数组。您还必须初始化数组,我已经修改了应答器。它工作正常,但并不像我预期的那样,因为它在this.user中保存了所有(用户名和密码)元素,而不是将this.user(x.username)和this.pass(x.password)分开。很高兴它有所帮助。