如何将数字数组转换为字符串?

huangapple go评论72阅读模式
英文:

How can I convert an array of numbers to strings?

问题

I can't convert array's numbers into strings. What is wrong with my code?

我无法将数组中的数字转换为字符串。我的代码有什么问题?

I also tried: this.userIds.toString().split(',')

我还尝试过:this.userIds.toString().split(',')

collectIds() {
  this.array.forEach((e, i) => {
    // [8, 8, 8, undefined, undefined, undefined]
    if (this.array[i].details.user_id !== undefined) {
      this.userIds.push(this.array[i].details.user_id)
      // [8, 8, 8]
    }
  });
  
  this.userIds.map(e => e.toString())
  console.log("userIds: ", this.userIds)
  // [8, 8, 8]
}
英文:

I can't convert array's numbers into strings. What is wrong with my code?

I also tried: this.userIds.toString().split(',')

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

collectIds() {
  this.array.forEach((e, i) =&gt; {
    // [8, 8, 8, undefined, undefined, undefined]
    if (this.array[i].details.user_id !== undefined) {
      this.userIds.push(this.array[i].details.user_id)
      // [8, 8, 8]
    }
  });
  
  this.userIds.map(e =&gt; e.toString())
  console.log(&quot;userIds: &quot;, this.userIds)
  // [8, 8, 8]
}

<!-- end snippet -->

答案1

得分: 1

map 创建一个包含转换后元素的新数组。它不会修改旧数组。

您可以将 this.userIds 重新赋值为新数组。

this.userIds = this.userIds.map(e => e.toString());

或者您可以使用 forEach 并在迭代过程中修改数组。

this.userIds.forEach((e, i, a) => a[i] = e.toString());
英文:

map creates a new array with the transformed elements. It does not modify the old one.

You could reassign this.userIds to the new array.

this.userIds = this.userIds.map(e =&gt; e.toString());

Or you could use forEach and mutate the array while iterating.

this.userIds.forEach((e, i, a) =&gt; a[i] = e.toString());

答案2

得分: 0

Array.prototype.map() 返回一个新的数组。

如果这是您的意图,您需要重新分配 this.userIds

this.userIds = this.userIds.map(e => e.toString())
英文:

Array.prototype.map() returns a new array.

You will need to reassign this.userIds if this is your intention.

this.userIds = this.userIds.map(e =&gt; e.toString())

huangapple
  • 本文由 发表于 2023年7月20日 22:03:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76730707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定