简体   繁体   中英

I want to write a JavaScript function that reverse a number

I'm learning JavaScript and I really want to understand why this function is not working. Please explain me what am I doing wrong here and how I could make it work. I really want to keep it simple like it is so I can understand what I'm doing wrong and right.

var input = prompt("Write a number");

function around() {
    for (var x = 0; x < input.lenght ; x++) {
        console.log(input.reverse());
    }
}

around();

This should do the trick. Strings don't have a reverse() method but arrays do:

function around() {
    var input = prompt("Write a number");

    if (!parseInt(input)) {
        return null; // Or do something with bad input
    }

    return parseInt(input.split('').reverse().join(''));
}

When I read your function, it seems like it would print your reversed string n times, where n is the length of your string. In any case, it looks like you're trying to reverse a string, so let's move on.

There is no "reverse" function built-in to Javascript to reverse strings. There is, however, a way to reverse arrays (using .reverse()). You can split your string into an array quite easily, ie using input.split(""). You can then reverse the array, and call .join("") on it to turn your array back into a string again.

But I can't really be sure what you want your function to do if you don't say anything about it.

What is returned from prompt is a String type, and reverse() Method is used for Array type.

So the most simple way to reverse a string is to split it into an array of characters, reverse it, join the characters back into a string, you can then parse that into a number if you would like.

 var input = prompt("Write a number"); function around() { input = parseInt(input.split('').reverse().join('')); console.log(input); } around(); 

Your problem here is that input is a string, and the string prototype has no reverse method. To accomplish this you'd have to do something like input.split('').reverse().join('') . split('') converts a string to an array of characters. reverse() is an Array method that reverses an array in place. join('') combines each element of an array into a string, adding the argument in between each array element (an empty string in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM