¿Alguien puede explicar cuál es el error en el siguiente código?
function reverseString(str) { let reversedStr = ""; for (let i = 0; i < str.length; i++) { reversedStr.unshift(str[i]); return str; } } console.log( reverseString("hello") )Necesita una matriz para hacer unshift y el regreso fuera del ciclo
const reverseString = str => { const rev = []; for (let i = 0; i < str.length; i++) rev.unshift(str[i]) return rev.join("") }; console.log( reverseString("hello") )pero aquí hay una línea
const reverseString = str => str ? [...str].reverse().join("") : str; console.log( reverseString("hello") ) function reverseString(str) { let arr = []; for (let i = 0; i < str.length; i++) { arr.unshift(str[i]); } return arr.join(""); } console.log(reverseString("hello")); Si tenía la intención de hacer la cadena al revés sin usar una función de utilidad, puede hacerlo como se muestra a continuación. Si la longitud de la cadena es n , entonces la complejidad temporal del siguiente código es O(n/2) .
function reverseString(str) { // get single characters into array const arrOfChars = str.split(""); // get the half size of the array const halfLengthOfArr = Math.floor(arrOfChars.length / 2); // start index let i = 0; // swap chars until reach the middle of the array // hello // ^ ^ // oellh // ^ ^ // olleh while (i < halfLengthOfArr) { // swap coupterparts from start and end with same distance const start = arrOfChars[i]; arrOfChars[i] = arrOfChars[arrOfChars.length - (i + 1)]; arrOfChars[arrOfChars.length - (i + 1)] = start; i++; } // return the output array as a string return arrOfChars.join(""); } console.log(reverseString("hello"));Recomiendo alejarse por completo del enfoque sin turnos según sus requisitos.
Por lo tanto, he diseñado dos versiones de su función para usted y todas se basan únicamente en funciones de matriz.
Versión compacta:
function reverseString(str) { return str.split("").reverse().join("") } console.log( reverseString("hello") )Versión más larga (más fácil de entender):
function reverseString(str) { const characters = str.split("") const charactersReversed = characters.reverse() return charactersReversed.join("") } console.log( reverseString("hello") )Espero que haya ayudado, incluso si no atiendo su solicitud de cambio de turno.
Por último, pero no menos importante, también modifiqué su código inicial con su función de cambio de marcha, incluso si no recomiendo este código en producción:
function reverseString(str) { const reversedStr = []; for (let i = 0; i < str.length; i++) { reversedStr.unshift(str[i]); } return reversedStr.join(""); } console.log( reverseString("hello") )