[英]Appending to an array (JavaScript)
I'm trying to append to an array, with .push
. 我正在尝试使用
.push
追加到数组。 It seems that this does not happen, and here is my code. 看来这不会发生,这是我的代码。
if(message.content.toLowerCase().startsWith('!startvote')) {
let args = message.content.slice(1).trim().split(/ +/g);
let command = args.shift().toLowerCase();
let totalOptions = [];
message.channel.send(`Starting vote. Use !vote1, to vote for the first option, !vote2 for the second, etc.`);
message.channel.awaitMessages(msg => msg.content.startsWith('!vote1'), {time: 10000})
.then(collected => message.channel.send(collected.size + ' users voted for \`option 1\`'))
.then(collected => totalOptions.push({'optionOne': collected.size}))
.catch(console.error);
message.channel.awaitMessages(msg => msg.content.startsWith('!vote2'), {time: 10000})
.then(collected => message.channel.send(collected.size + ' users voted for \`option 2\`'))
.then(collected => totalOptions.push({'optionTwo': collected.size}))
.catch(console.error);
}
Whenever I try logging this somewhere else, the array returns empty. 每当我尝试将此日志记录到其他地方时,数组将返回空。
Edit: here is the new code 编辑:这是新代码
message.channel.awaitMessages(msg => msg.content.startsWith('!vote1'), {time: 10000})
.then(collected => message.channel.send(collected.size + ' users voted for \`option 1\`'))
.then(collected => totalOptions.push({'optionOne': collected.size}))
.then(console.log(totalOptions))
.catch(console.error);
message.channel.awaitMessages(msg => msg.content.startsWith('!vote2'), {time: 10000})
.then(collected => message.channel.send(collected.size + ' users voted for \`option 2\`'))
.then(collected => totalOptions.push({'optionTwo': collected.size}))
.then(console.log(totalOptions))
.catch(console.error);
Because of asynchronous code, you may be outputting totalOptions befroe it's updated inside a then block. 由于异步代码的缘故,您可能会在将代码更新到then块中之前输出totalOptions。
try adding an extra then() block after the one where you push and console.log(totalOptions) in the new then(). 尝试在您推送的内容之后添加一个额外的then()块,然后在新的then()中添加console.log(totalOptions)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.