A palindrome string is a string that reads the same forward and reverse, such as "noon", "abcba"
How to verify that the string is a palindrome? Here are a few methods for reference:
First use the split method of the string to convert it into an array, then use the array to flip, and finally convert it into a new string, and compare the two to judge
function checkStr(str) {
return str === str.split('').reverse().join('')
}
checkStr("noon"); //true
checkStr("noonl"); //false
The original str is cycled in reverse order to generate a new str1, and the two are compared and judged
function checkStr(str){
let len = str.length;
let str1 = "";
for(let i=len-1; i>=0;i--){
str1+=str[i];
}
return str1 === str
}
checkStr("noon"); //true
checkStr("noonl"); //false
Use the charAt method of the string to get the characters at the front and rear symmetrical positions, perform a cyclic comparison, store the result in result_arr, and finally judge whether result_arr contains unequal (false) data, and if so, the string is not a palindrome character String, conversely, is a palindrome string
function checkStr(str){
let len = str.length;
let result_arr = [];
for(let i=0; i<len;i++){
// 依次进行前后比对
const result = str.charAt(i) === str.charAt(len-1-i)
result_arr.push(result)
}
return result_arr.indexOf(false) === -1
}
checkStr("noon"); //true
checkStr("noonl"); //false