You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现输入单词列表返回所有回文单词的功能?

找出单词列表中的所有回文单词

首先明确:JavaScript函数完全可以返回数组,数组就是用来装多个值的,这正是你需要的——把所有回文单词放在数组里返回就行。

先说说你代码里的几个问题:

  • 函数定义了参数str但根本没用到,反而硬编码了内部的words字符串,这样函数没法接收外部传入的单词列表
  • 反转单词的循环写错了:内层循环用了i变量(和外层循环的i冲突),而且逻辑是把整个单词重复加,不是反转字符
  • 用return myWords[i]会直接终止函数,只能返回第一个匹配的回文,没办法收集所有结果
  • 存在多余大括号、分号这类语法错误

下面给两种可行的写法:

写法一:用for循环手动收集回文单词

function getPalindromeWords(wordList) {
  // 兼容传入字符串或数组的情况
  const words = typeof wordList === 'string' ? wordList.split(' ') : wordList;
  const palindromes = []; // 用数组存所有回文单词

  for (const word of words) {
    // 反转单词:转成数组→反转→拼接回字符串
    const reversedWord = word.split('').reverse().join('');
    if (word === reversedWord) {
      palindromes.push(word); // 符合条件就放进数组
    }
  }

  return palindromes; // 返回装着所有回文的数组
}

// 测试
const testWords = "a aa aaa aah aahed aahing aah saal aalii aaliis aals aam";
console.log(getPalindromeWords(testWords));
// 输出:['a', 'aa', 'aaa']

写法二:用数组filter方法(更简洁)

数组的filter方法可以直接筛选符合条件的元素,一步到位:

function getPalindromeWords(wordList) {
  const words = typeof wordList === 'string' ? wordList.split(' ') : wordList;
  return words.filter(word => word === word.split('').reverse().join(''));
}

// 测试
const testWords = "a aa aaa aah aahed aahing aah saal aalii aaliis aals aam";
console.log(getPalindromeWords(testWords));

如果不想用函数,直接写代码处理也可以:

const words = "a aa aaa aah aahed aahing aah saal aalii aaliis aals aam".split(' ');
const palindromes = words.filter(word => word === word.split('').reverse().join(''));
console.log(palindromes);

内容的提问来源于stack exchange,提问作者pluc516

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 23:20:08