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

How to use JavaScript to determine whether it is a palindrome number

青灯夜游
Release: 2021-11-26 16:54:04
Original
3982 people have browsed it

Method: 1. Use toString() and split() to convert the number into an array; 2. Use reserve() to flip the order of the array elements; 3. Use join() and Number() to convert the flipped array Convert to a number; 5. Use the "===" operator to compare whether the original number and the flipped number are equal. If they are equal, it is a palindrome number.

How to use JavaScript to determine whether it is a palindrome number

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Palindromes refer to integers that read the same in forward order (from left to right) and reverse order (from right to left).

For example, "121" is a palindrome number.

So how to use JavaScript to determine whether it is a palindrome?

Implementation idea: Use array

  • First convert a number into a string

  • Then convert the string into Split into characters and store them in an array, that is, convert them into a character array

  • Then use the reserve() method to flip the array and reverse the order of the elements in the array

  • Then convert the flipped array into numbers

  • Finally use === to compare to see if the original number and the flipped number are equal , if equal, it is a palindrome number.

Implementation code:

var x=121;
var str = x.toString()  //转化为字符串
var arr = str.split('') //转化为数组
var res = Number(arr.reverse().join(''))
if(x===res){
	console.log(x +"是一个回文数");
}else{
	console.log(x +"不是一个回文数");
}
Copy after login

How to use JavaScript to determine whether it is a palindrome number

[Related recommendations: javascript learning tutorial

The above is the detailed content of How to use JavaScript to determine whether it is a palindrome number. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!