仅反转奇数长度的单词 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/6 21:00:17

我们需要编写一个 JavaScript 函数,该函数接收一个字符串并反转字符串中包含奇数个字符的单词。

如果字符串中的任何子字符串在两端被两个空格封装,或者出现在末尾或开头并且后面或前面有一个空格,则该子字符串可以算作一个单词。

假设以下是我们的字符串 −

const str = 'hello beautiful people';

奇数长度的单词是 −

hello
beautiful

示例

让我们为该函数编写代码。

const str = 'hello beautiful people';
const idOdd = str => str.length % 2 === 1;
const reverseOddWords = (str = '') => {
   const strArr = str.split(' ');
   return strArr.reduce((acc, val) => {
      if(idOdd(val)){
         acc.push(val.split('').reverse().join(''));
      return acc;
   };
   acc.push(val);
   return acc;
   }, []).join(' ');
};
console.log(reverseOddWords(str));

输出

以下是控制台中的输出 −

olleh lufituaeb people

相关文章


有用资源