英文:
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) => {
// [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]
}
<!-- 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 => e.toString());
Or you could use forEach
and mutate the array while iterating.
this.userIds.forEach((e, i, a) => 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 => e.toString())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论