Home > Web Front-end > JS Tutorial > body text

Analysis of how to reverse numbers through javascript

藏色散人
Release: 2021-08-10 11:26:04
Original
4065 people have browsed it

"Reverse numbers" means outputting numbers in reverse order. For example, a number 12345, after reversal, is 54321; then in "Quickly reverse and output a positive integer through a PHP program" we explain how Reverse a number through PHP. Friends who are interested can learn about it~

The focus of this article is to explain how to reverse a number through javascript.

Without further ado, I will go directly to the code:

javascript to reverse the numbers:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
    function reverse_a_number(n)
    {
        n = n + "";
        return n.split("").reverse().join("");
    }
    console.log(reverse_a_number(32243));

</script>
</body>
</html>
Copy after login

Then open the console to view the reversal result :

Analysis of how to reverse numbers through javascript

In the above code, I gave an example number "32243", which is obviously reversed to "34223".

In the js code in the above example, you need to master 3 methods:

1.split() method: used to split a string into a string array, its syntax is " stringObject.split(separator,howmany)”;

parameters respectively represent:

separator,字符串或正则表达式,从该参数指定的地方分割 stringObject。
howmany,该参数可指定返回的数组的最大长度。如果设置了该参数,返回的子串不会多于这个参数指定的数组。如果没有设置该参数,整个字符串都会被分割,不考虑它的长度。
Copy after login

→Note: If an empty string ("") is used as separator, then each character in stringObject will be separated. String.split() performs the opposite operation of Array.join .

2.reverse() method: used to reverse the order of elements in an array, its syntax is "arrayObject.reverse()";

→Note: This method will change the original array but not create a new array.

3.join() method: used to put all the elements in the array into a string. The elements are separated by the specified delimiter. The syntax is "arrayObject. join(separator)"; its parameter separator specifies the separator to be used; if this parameter is omitted, a comma is used as the separator.

Finally, I would like to recommend "JavaScript Basics Tutorial" ~ Welcome everyone to learn ~

The above is the detailed content of Analysis of how to reverse numbers through javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template