Home  >  Article  >  Web Front-end  >  How to use JavaScript to determine whether it is a palindrome number

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

青灯夜游
青灯夜游Original
2021-11-26 16:54:044007browse

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 +"不是一个回文数");
}

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!

Statement:
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