If you want something to happen over and over again, use a loop - That’s what they’re for :-)
Besides, it makes no sense to launch a Error
inside the block try
just to catch it right away. And the Error
that you have created neither message, so nothing useful will be shown (only "Error").
You don’t need Error
nor of try
/catch
. If you want an error message to be shown if the result is NaN
, place it inside the if
even:
function escrever(numbers) {
const doc = document.querySelector("#seletor");
doc.innerHTML = numbers;
}
while (true) {
var p = parseFloat(prompt("Digite um número"));
if (isNaN(p)) {
alert('Não foi digitado um número');
} else {
escrever(p);
break; // sai do while
}
}
<p id="seletor"></p>
while (true)
creates a loop "infinite" - it repeats itself until it finds some break
, and in that case the break
is only called when a valid number is entered (but if you want this to keep repeating itself indefinitely, simply remove the break
).
To another answer suggested using recursion (i.e., creating a function and calling it within itself), but this is not a good idea, because each recursive call will occupying space in the execution stack, and this can burst the stack if it occurs many times. Even if it does not burst, it makes no sense to keep calling several times the same function within itself, when a simple loop resolves.
Another detail is that in the same answer, the function escrever
is created within the function setNumber
, and this causes a new function to be created every time setNumber
is called. That is, in addition to improperly using recursion (occupying the execution stack without need), it still creates several functions for nothing. In short, don’t do it :-) Use the loop above which is already sufficient.
To learn more about recursion (what it is, and especially when not using it), read here, here, here, here and here.
Javascript (fortunately? :P) does not have
goto
explicit. One way to do this is withwhile
, but the logic is a little different. :)– Luiz Felipe
@Luizfelipe did not understand, could explain better or make a code showing an example, please?
– Gimieski
Try to improve your question first. : ) For example, instead of putting code per image, put it in text. Also try to describe the problem a little better.
– Luiz Felipe
@Luizfelipe formulated better
– Gimieski