[英]Values are being duplicated when being pushed to array
When I run this code I get the last element duplicated for all entries.当我运行此代码时,我会为所有条目复制最后一个元素。 I am trying to add a new role in discord and save some entries to my json file regarding role details idk but I can't seem to do it.
我正在尝试在 discord 中添加一个新角色,并将一些关于角色详细信息 idk 的条目保存到我的 json 文件中,但我似乎做不到。
I have added the declarations for the data nd list variables.我添加了数据和列表变量的声明。
let data = fs.readFileSync('roles.json')
var list = JSON.parse(data)
var details = {nickname:"",channel:"",message:"",role:"",emoji:"",raw:"",error:""}
let sections = ['A','B','C','D']
var bar = new Promise((resolve, reject) => {
sections.forEach(async function (value, index, array) {
let role = await message.guild.roles.create({ data: { name: `Section ${value}` } })
details.nickname = value
details.channel = '12345567'
details.message = '1233454676'
details.role = role.id
details.error = '12443566'
list.push(details)
if (index === array.length - 1)
resolve()
});
});
bar.then(() => {
console.log(list);
});
Output Output
[
{
nickname: '',
channel: '',
message: '',
role: '',
emoji: '',
raw: '',
error: ''
},
{
nickname: 'D',
channel: '12345567',
message: '1233454676',
role: '784672976855498813',
emoji: '',
raw: '',
error: '12443566'
},
{
nickname: 'D',
channel: '12345567',
message: '1233454676',
role: '784672976855498813',
emoji: '',
raw: '',
error: '12443566'
},
{
nickname: 'D',
channel: '12345567',
message: '1233454676',
role: '784672976855498813',
emoji: '',
raw: '',
error: '12443566'
},
{
nickname: 'D',
channel: '12345567',
message: '1233454676',
role: '784672976855498813',
emoji: '',
raw: '',
error: '12443566'
}
]
You are mutating the same object repeatedly before pushing a reference to it into the list
array.在将对它的引用推送到
list
数组之前,您正在反复变异相同的 object。
Either declare a new details
object inside the forEach callback each iteration...在每次迭代的 forEach 回调中声明一个新的
details
object ...
let sections = ['A', 'B', 'C', 'D'] const list = [] sections.forEach((value) => { const details = {} details.nickname = value list.push(details) }); console.log(list)
...or if the above is not possible, push a clone of the details
object into list
instead of a reference to the original details
object. ...或者如果上述情况不可行,请将
details
object 的克隆推送到list
,而不是对原始details
object 的引用。
let sections = ['A', 'B', 'C', 'D'] const list = [] const details = {} sections.forEach((value) => { details.nickname = value list.push({...details}) }); console.log(list)
use for...of
instead, don't use async...await
inside foreach
loop使用
for...of
代替,不要在foreach
循环中使用async...await
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.