Problem with Javascript String

Asked

Viewed 44 times

0

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        let numero = window.prompt("Informe um número para ver o reverso: ");
        let reverso = [];
        let tamanho = numero.length;
        parseInt(numero, 10);

        for(let k = 0; k<tamanho; k++){
            reverso[k] = numero % 10;
            numero = numero / 10;
        }

        document.write(`${reverso}`);

    </script>
</body>
</html>

The program asks to show the reverse of a number, ex: 145, reverse: 541. I have a problem when converting the number I read(string) into an integer using parseint(). Even after conversion, the number variable apparently remains a string and the result of the execution is not certain. Please tell me where I’m going wrong.

  • Alters parseInt(numero, 10); for numero = parseInt(numero, 10);

  • I did it the other way the guy sent it down there and it worked. But I also did it your way and the output is like this: 2,2,200000000000003,5,220000000000001. And in Vscode itself is saying that the variable number is like String. I would like to understand why the conversion is not working.

  • That’s because you’re missing a few details in the rest of the code to make it right. In particular he is making a division with floating comma and must make entire division with numero = Math.floor(numero / 10). Then you are typing the array directly into the page that will give you commas, instead you should use Join with document.write(reverso.join(''));

1 answer

0

The parseInt(numero, 10); converts a number into a string, and so separate does nothing as its return is not used.

You can do it like this:

const numero = window.prompt("Informe um número para ver o reverso: ");
const reverso = numero.split('').reverse().join('');

document.write(reverso);

The idea/logic is:

  • the prompt gives you a String
  • with .split('') separates the String in characters (you create a Array)
  • with .reverse() you reverse the order of Array character
  • with .join('') you paste these characters back into the Array in a String again...

Browser other questions tagged

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