Javascript - Stop Condition

Asked

Viewed 93 times

-1

I want to ask several names typed via prompt, and have some stop condition, I thought this condition being a number, but I did not succeed.

let nomes = []
let dado = ""

console.log(typeof(dado))
while(dado == String){
    dado = prompt("Digite um nome para continuar o programa, ou digite o número 0 para encerra-lo.")
    if(typeof(dado) == String) nomes.push(dado)
    if(dado == 0) parseInt(dado)
}

for(i = nomes.length; i == 0; i--){
    console.log(nomes[i])
}
  • 2

    if(dado == 0) break

  • But why would I need standstill condition if the very prompt has the function cancelar? It would not be better to change the text? Digite um nome para continuar o programa, ou clique em cancelar para encerra-lo.

1 answer

0


Your code has some problems:

  1. String is a function, when comparing it with the variable dado will always return false

  2. The return of expression typeof <variavel> will be a string, and if type is string will be "string" (all in tiny)

  3. No reason to evaluate the type returned by the function prompt, semrpe will be a string, even if you type a number, for example, when you type 0, it will return "0"

  4. Unless the name array is empty its loop for will never be executed, the way the condition should be i != 0

let nomes = []
let dado = ''

// Se for digitado '0', o loop é encerrado
while(dado !== '0') {
    dado = prompt('Digite um nome para continuar o programa, ou digite o número 0 para encerra-lo.')

    // Se não for digitado '0' adiciona aos nomes
    if (dado !== '0') nomes.push(dado)
}

// Uma sintaxe diferente para fazer o loop
for (const nome of nomes) console.log(nome)

  • I liked the solution, but ifs and inline Fors without keys makes understanding difficult, even the JS allowing this.

  • It is a matter of point of view, considering that the question uses them, the user knows how it works

Browser other questions tagged

You are not signed in. Login or sign up in order to post.