只反转字符串中的某些单词

时间:2018-10-04 19:43:09

标签: javascript string function foreach reverse

我正在编写一个函数,以仅反转一定长度(在这种情况下为5个或更多)的字符串中的单词。如果长度那么长,我可以使每个单词都反向,但是我很难将正确的单词返回到字符串。

function spinWords(string){
  let splitString = string.split(" ");
  console.log(splitString);
  splitString.forEach(function(word) {
      if (word.length >= 5) {
        console.log(word.split("").reverse().join(""));
        return word.split("").reverse().join("");
        
     } else if (word.length < 5) {
        console.log(word);
        return word;
    }
    //should something go here?
  });
  console.log(splitString); //returns same output as when called at top of function
  newString = splitString.join(" ");
  console.log(newString);
}

spinWords("Jammerson is the best friend ever");

或者,当我将forEach()函数保存到新变量中时,该函数将返回未定义状态。我不确定我缺少哪一块。预先感谢!

3 个答案:

答案 0 :(得分:0)

首先,您的函数需要返回一个值。另外,尝试创建另一个具有新值的字符串:

function spinWords(string){

  let newString = ''; // added this here

  let splitString = string.split(" ");

  splitString.forEach(function(word, index) {
     if (word.length >= 5) {
        newString += word.split("").reverse().join("");  // added this here            
     } else if (word.length < 5) {
        newString += word;  // added this here
    }
    // add a space between characters, unless its the last char
    if(splitString.length > index + 1) {
        newString += ' ';  // added this here
    }
  });

  return newString;
}

console.log(spinWords("Jammerson is the best friend ever"));

答案 1 :(得分:0)

您只需要一点修复:

function spinWords(string){
  let splitString = string.split(" ");
  console.log(splitString);
  splitString.forEach(function (word, index, arr)  {
      if (word.length >= 5) {
        console.log(word.split("").reverse().join(""));
        arr[index] = word.split("").reverse().join("");
        
     } else if (word.length < 5) {
        console.log(word);
        arr[index] = word;
    }
    //should something go here?
  });
  console.log(splitString); //returns same output as when called at top of function
  newString = splitString.join(" ");
  console.log(newString);
}

spinWords("Jammerson is the best friend ever");

答案 2 :(得分:0)

您不仅想用forEach迭代数组,还想map将其替换为一个新的反向单词数组:

 splitString = splitString.map(function(word) {

然后将使用返回的单词。可以简化为此一线:

 const reverseWord = str => str.length >= 5 ? str.split``.reverse().join`` : str;
 const spinWords = str => str.split` `.map(reverseWord).join` `;