JavaScript 函数:反转长单词 (Kata 挑战)
function reverseLongWords(str) { // 将字符串分割成单词数组 const words = str.split(' ');
// 遍历每个单词,如果长度大于等于 5,则反转 for (let i = 0; i < words.length; i++) { if (words[i].length >= 5) { words[i] = words[i].split('').reverse().join(''); } }
// 将单词连接成字符串并返回 return words.join(' '); }
// 示例用法: reverseLongWords('Hello world'); // 返回 'Hello world' reverseLongWords('This is a test'); // 返回 'sihT is a tset' reverseLongWords('The quick brown fox jumps over the lazy dog'); // 返回 'The quick nworb xof spmuj revo eht yzal god'
原文地址: https://www.cveoy.top/t/topic/mBTH 著作权归作者所有。请勿转载和采集!