最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Reverse a number in javascript - Stack Overflow

programmeradmin1浏览0评论

I want to reverse a number t following the tutorial.First I have passed a number as a parameter. I have converted the number to string with to String function. Then I used split("").reverse().join("") to reverse the number. My code is as follows:

<script type="text/javascript">


        function reverse_the_string(num) {
            num = String(num);
            // str = num.toString;
            num.split("").reverse().join("");
            return;
        }
        console.log(reverse_the_string(56789));
    </script>

However I get an error undefined? Can anyone explain what is the wrong?

I want to reverse a number t following the tutorial.First I have passed a number as a parameter. I have converted the number to string with to String function. Then I used split("").reverse().join("") to reverse the number. My code is as follows:

<script type="text/javascript">


        function reverse_the_string(num) {
            num = String(num);
            // str = num.toString;
            num.split("").reverse().join("");
            return;
        }
        console.log(reverse_the_string(56789));
    </script>

However I get an error undefined? Can anyone explain what is the wrong?

Share Improve this question asked Apr 18, 2016 at 6:52 pallavidestiny22pallavidestiny22 3353 gold badges9 silver badges19 bronze badges 4
  • 2 One liner: return String(num).split("").reverse().join(""); – Rayon Commented Apr 18, 2016 at 6:54
  • @SatejS: - Step 1: num.split("") return an array with the digits from given number. For example 12345 --> [ '1', '2', '3', '4', '5' ] - Step 2: .reverse() return an array with elements in reverse order. So [ '1', '2', '3', '4', '5' ] will bee [ '5' , '4', '3', '2', '1' ] - Step 3: .join('') is Array method to create a string from elements. So [ '5' , '4', '3', '2', '1' ] will bees '54321' The approach is correct. He just forget return value :) – Dong Nguyen Commented Apr 18, 2016 at 7:00
  • What i did was return instead of return num, I think that return too passes the result? I want to know why does return only do not work? – pallavidestiny22 Commented Apr 18, 2016 at 7:04
  • You need to specify what you want to return. There is no way the JavaScript parser can guess which variable you want to be returned. Therefore you need to specify it yourself. Imagine being an a shop and you ask the employee to sell you something instead of to sell you a blue ball. For the first question the employee still don't know what you want. – Mark Baijens Commented Jul 3, 2019 at 12:12
Add a ment  | 

5 Answers 5

Reset to default 5

You do not return the result. Use

return num.split("").reverse().join("");

If you use just return, then undefined is returned.

function reverse_the_string(num) {
    return String(num).split("").reverse().join("");
}

document.write(reverse_the_string(56789));

Caveat: Reversing works only with small numbers!

The solution of casting the number into a string and reversing the string is a good solution, BUT it doesn't cover all the cases. There are 2 cases that need to be addressed:

  1. Reversing a negative number it doesn't retain the sign.
  2. Reversing a number that ends with zero(s), after reversing you will have leading zeros, e.g. 12300 the reverse will be "00321" when it should be "321".

Using Regular function

var reversed = parseFloat(num.toString().split("").reverse().join()) * Math.sign(num);

Using Arrow Function

var reversed = num => parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num);

Try this (Recursive Method)

 
function reverseNum(num) {
    if(num == 0)return 0;
    let x = Math.pow(10, (num + '').length - 1);
    return (num % 10) * x + reverseNum(Math.floor(num / 10));
} 
console.log(reverseNum(432));

Convert the number variable to a string:

var n = 4557
n = n.toString();

then execute the below code.

 //**Reverse the Number In javascript** 
 var result = "";
 function reverseNumber(n){
   // reverse the number via loop 
   for(var i=x.length-1; i>=0; i--){  
     result+=n[i];
   }
   return Number(result)
 }
 var x = prompt("Enter a number : ");
 console.log(reverseNumber(x))
            

In order to reverse number/ string you can refer this method: (without using slice() and substring() methods)

function reverse(str) {
  var rev = "";
  number = parseInt(str);
  for (; number > 0;) {
    rev += number % 10;
    number = Math.floor(number / 10)
  }
  return rev;
}
发布评论

评论列表(0)

  1. 暂无评论