【问题标题】:reverse only certain words in string仅反转字符串中的某些单词
【发布时间】:2018-10-04 19:43:08
【问题描述】:

我正在编写一个函数来仅反转字符串中具有一定长度的单词,在本例中为 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() 函数保存到一个新变量中时,该函数返回为未定义。我不确定我缺少哪一块。提前致谢!

【问题讨论】:

  • 使用map 而不是forEach

标签: javascript string function foreach reverse


【解决方案1】:

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

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"));

【讨论】:

    【解决方案2】:

    你只需要一点点修复:

    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");

    【讨论】:

      【解决方案3】:

      您想将mapforEach 一起迭代到一个新的反转单词数组中,而不是只迭代数组:

       splitString = splitString.map(function(word) {
      

      然后将采用返回的单词。这可以缩短为这个 oneliner:

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

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 2015-12-13
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多