如果一个字符串从前向后读与从后向前读都相同,那么它就是一个回文。例如,dad 从前向后读都相同。所以单词dad 是一个回文。同样,madam 也是一个回文。
示例 1:使用 for 循环检查回文
// program to check if the string is palindrome or not
function checkPalindrome(string) {
// find the length of a string
const len = string.length;
// loop through half of the string
for (let i = 0; i < len / 2; i++) {
// check if first and last string are same
if (string[i] !== string[len - 1 - i]) {
return 'It is not a palindrome';
}
}
return 'It is a palindrome';
}
// take input
const string = prompt('Enter a string: ');
// call the function
const value = checkPalindrome(string);
console.log(value);
输出
Enter a string: madam It is a palindrome
在上面的程序中,checkPalindrome()
函数接收用户的输入。
- 使用 length 属性计算字符串的长度。
- 使用 for 循环迭代字符串的一半。
if
条件用于检查第一个字符和对应的最后一个字符是否相同。此循环一直执行到字符串的一半。 - 在迭代过程中,如果字符串的任何字符与其对应的最后一个字符串不相等,则该字符串不被认为是回文。
示例 2:使用内置函数检查回文
// program to check if the string is palindrome or not
function checkPalindrome(string) {
// convert string to an array
const arrayValues = string.split('');
// reverse the array values
const reverseArrayValues = arrayValues.reverse();
// convert array to string
const reverseString = reverseArrayValues.join('');
if(string == reverseString) {
console.log('It is a palindrome');
}
else {
console.log('It is not a palindrome');
}
}
//take input
const string = prompt('Enter a string: ');
checkPalindrome(string);
输出
Enter a string: hello It is not a palindrome
在上面的程序中,使用 JavaScript 中可用的 内置方法 来检查回文。
- split('') 方法将字符串转换为单个 数组 字符。
const arrayValues = string.split(''); // ["h", "e", "l", "l", "o"]
reverse()
方法会颠倒数组中元素的顺序。// ["o", "l", "l", "e", "h"] const reverseArrayValues = arrayValues.reverse();
join('')
方法将数组的所有元素连接成一个字符串。const reverseString = reverseArrayValues.join(''); // "olleh"
- 然后使用
if...else
语句检查字符串和反转后的字符串是否相等。如果它们相等,则该字符串是回文。
注意:多行代码可以合并,写在一行中。
const reverseString = string.split('').reverse().join('');
另请阅读