How do I make the function not return the value if the number is not binary

Asked

Viewed 49 times

0

I am trying to make a limiter so that every time the user type a number that is not binary, receive an alert with the message "Write a binary number" however the problem is that the code sends the message, but continues running the function

function Bin2Dec ()
{
    const numeros = document.getElementById("char-input").value;
    if (numeros === '') 
    {
        return alert("Por favor, escreva um numero binário");
    }
    numeros.split('').map((char) => {
        if (char !== '0' && char !== '1') return alert("Por favor, escreva um numero binário");
    });
    const decimal = parseInt( numeros, 2 );
    document.getElementById("convertido").innerHTML = numeros + " na base decimal é: " + decimal;        
}    

inserir a descrição da imagem aqui

  • For those who want to see the site https://sancheesandre.github.io/Bin2Dec/

1 answer

1

Hello @Sancheesdev all good?

The logic is correct, the problem in question is that by making the verification within the map of the list the return will occur only for the map scope. I recommend doing the validation in the same function. For example:

function Bin2Dec ()
{
    const numeros = document.getElementById("char-input").value;
    if (numeros === '') 
    {
        return alert("Por favor, escreva um numero binário");
    }

    const hasNonBinaryDigits = numeros.split('').some(char => char !== '0' && char !== '1');
    if(hasNonBinaryDigits) { 
       return alert("Por favor, escreva um numero binário");
    }

    const decimal = parseInt( numeros, 2 );
    document.getElementById("convertido").innerHTML = numeros + " na base decimal é: " + decimal;        
} 
  • It worked, thank you very much! I’m new not programming so I’m still understanding how the "map" works. I tried several ways to separate the code, but unsuccessfully haha

Browser other questions tagged

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