英文:
How do I run this loop until there are no more objects in the array?
问题
当数组达到 []
时,我试图运行一个 while 循环,但它会崩溃。
这是我正在运行的代码:
const mineflayer = require('mineflayer');
let contas = require('./accounts');
let fila = []
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function main() {
async function start(conta) {
await sleep(1000);
fila.logged = true;
fila.shift();
}
async function queueStarter() {
let loop = 1;
if (fila.length >= loop && fila.length != 'undefined') {
while (fila[0].logged == false) {
start(fila[0]);
await sleep(4000);
}
} else console.log('Reached array end')
}
for (key in contas) {
let conta = contas[key];
fila.push(conta);
}
queueStarter()
}
main();
这是控制台输出:
PS C:\Users\Zwei\.vscode\IDKHowToCode> node .\StackExcample.js
C:\Users\Zwei\.vscode\IDKHowToCode\StackExcample.js:20
while (fila[0].logged == false){
^
TypeError: Cannot read properties of undefined (reading 'logged')
at queueStarter (C:\Users\Zwei\.vscode\IDKHowToCode\StackExcample.js:20:20)
Node.js v18.12.1
我希望它在 fila
数组中没有更多对象时停止。为什么它在应该停止时没有停止呢?
英文:
I'm trying to run a while loop, but when the array reaches [], it crashes.
This is what I'm running:
const mineflayer = require('mineflayer');
let contas = require('./accounts');
let fila = []
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function main() {
async function start(conta) {
await sleep(1000);
fila.logged = true;
fila.shift();
}
async function queueStarter() {
let loop = 1;
if (fila.length >= loop && fila.length != 'undefined') {
while (fila[0].logged == false) {
start(fila[0]);
await sleep(4000);
}
} else console.log('Reached array end')
}
for (key in contas) {
let conta = contas[key];
fila.push(conta);
}
queueStarter()
}
main();
This is the console:
PS C:\Users\Zwei\.vscode\IDKHowToCode> node .\StackExcample.js
C:\Users\Zwei\.vscode\IDKHowToCode\StackExcample.js:20
while (fila[0].logged == false){
^
TypeError: Cannot read properties of undefined (reading 'logged')
at queueStarter (C:\Users\Zwei\.vscode\IDKHowToCode\StackExcample.js:20:20)
Node.js v18.12.1
What I want is for it to stop when there are no more objects in the 'fila' array.
Why is it not stopping when it should?
答案1
得分: 0
@Barmar 建议了这个修复方法,而且它有效
在 queueStarter
函数中,将以下代码段:
while (fila[0].logged == false) {
修改为:
while (fila[0] && fila[0].logged == false){
这样会检查 fila[0]
是否存在并且是否已经被记录。
英文:
@Barmar suggested this fix and it works
on the queueStarter function, changing
while (fila[0].logged == false) {
to
while (fila[0] && fila[0].logged == false){
makes it check if there's something on fila[0] and if it's logged.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论