【问题标题】:Typescript - Trying to extract elements from array. Getting last element insteadTypescript - 试图从数组中提取元素。取而代之的是最后一个元素
【发布时间】:2020-08-26 16:20:41
【问题描述】:

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

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

【问题讨论】:

  • mc 对象与数组的内容有什么关系?无论如何,除此之外,您的问题是您在每次迭代时都会覆盖 this.user,这意味着您只会在循环结束时获得最后一个。
  • @Lior 是的,但我不想访问某个,我想访问所有这些。
  • @bugs 我的错,我更新了它。那么在这种情况下,你建议我做什么?
  • 所以,您已经有了一个数组(数据),其中包含您需要的所有内容。没有什么可提取的。 data 是你想要的:用户名/密码数组。

标签: arrays typescript


【解决方案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);
}

【讨论】:

  • 很高兴它有帮助。
【解决方案2】:

现在,您在每次迭代中都覆盖 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.user(x.username) 和 this.pass(x.password)
猜你喜欢
  • 2011-01-12
  • 2020-06-15
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多