How do you reverse a string in place in JavaScript?

前端 未结 30 2348
猫巷女王i
猫巷女王i 2020-11-22 00:29

How do you reverse a string in place (or in-place) in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse()<

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 00:46

    Reverse a String using built-in functions

    function reverse(str) {
      // Use the split() method to return a new array
      //  Use the reverse() method to reverse the new created array
      // Use the join() method to join all elements of the array into a string
      return str.split("").reverse().join("");
    }
    console.log(reverse('hello'));


    Reverse a String without the helpers

    function reversedOf(str) {
      let newStr = '';
      for (let char of str) {
        newStr = char + newStr
        // 1st round: "h" + "" = h, 2nd round: "e" + "h" = "eh" ... etc. 
        // console.log(newStr);
      }
      return newStr;
    }
    console.log(reversedOf('hello'));

提交回复
热议问题