如果字符串从前向或向后读取相同,则该字符串是回文。例如,dad 从前向后读都是一样的。所以爸爸这个词是一个回文。同样,madam也是回文。
示例 1: 使用 for 循环检查回文
// program to check if the string is palindrome or not function checkPalindrome(str) { // 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(str) { // 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('');