Node.js 为什么不是';是否在NodeJS中删除特定数组?
NodeJs:数组删除不起作用。如果没有一个循环,它就会被删除Node.js 为什么不是';是否在NodeJS中删除特定数组?,node.js,arrays,splice,Node.js,Arrays,Splice,NodeJs:数组删除不起作用。如果没有一个循环,它就会被删除 module.exports.run = (client, msg, args) => { //... //... song_search.res.videos.forEach(async (song, i) => { const songInfoER = await ytdl.getInfo(song.url).catch(err => { const remove = song_sear
module.exports.run = (client, msg, args) => {
//...
//...
song_search.res.videos.forEach(async (song, i) => {
const songInfoER = await ytdl.getInfo(song.url).catch(err => {
const remove = song_search.res.videos.splice(i, 1); //doesn't work here!
});
});
//...
//..
}
你如何努力做到这一点有很多问题。最大的一个是
.forEach()
没有承诺感知或异步感知,因此.forEach()
循环运行到完成,然后在不可预测的顺序下,您的承诺解析,并尝试执行.splice()
操作。由于这些都是以随机顺序进行的,因此不会产生可预测的结果。此外,song\u search.res.videos
不会在.forEach()
循环完成时更改
有很多不同的方法可以做到这一点。我建议对循环使用常规的,它支持承诺和异步。由于您希望在迭代时从数组中删除项,因此向后迭代数组也更容易,因此删除项不会改变迭代的其余部分:
// make the containing function async
const videos = song_search.res.videos;
for (let i = videos.length - 1; i > 0; i--) {
try {
const songInfoER = await ytdl.getInfo(videos[i].url);
// do something with songInfoER here
} catch(e) {
// no info for this video, remove it from the array
videos.splice(i, 1);
}
}
// song_search.res.videos will be updated here
“不行”是什么意思?请准确描述您期望发生的事情以及您观察到发生的事情。FIY,从一个数组中移除项目并不是很有意义,它是在用前述()/代码>迭代的过程中进行的。您可以收集要删除的索引,然后在迭代完成后一次删除所有索引(从数组末尾开始)。此外,.forEach()
不支持异步或承诺,因此,.splice()
的时间安排都很混乱(发生在.forEach()之后很久)
循环已经完成,它们甚至都没有按顺序发生。