This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//half index switch for loop | |
function reverseString6(str){ | |
let arr = str.split(''); | |
let len = arr.length, halfIndex = Math.floor(len / 2) - 1, tmp; | |
for (let i = 0; i <= halfIndex; i++) { | |
tmp = arr[len - i - 1]; | |
arr[len - i - 1] = arr[i]; | |
arr[i] = tmp; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//the reduceRight method | |
function reverseString5(str){ | |
return [...str].reduceRight((acc, cur)=> { | |
acc += cur | |
return acc | |
}, '') | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//the spread operator method | |
function reverseString4(str){ | |
return [...str] | |
.reverse() | |
.join('') | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//recursion | |
function reverseString3(str){ | |
if(!str){ | |
return str | |
}else{ | |
return reverseString3(str.slice(1)) + str[0] //ava Script + j then va Scriptj + a | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//the reverse method | |
function reverseString2(str){ | |
return str.split('').reverse().join('') | |
} | |
console.log(reverseString2('Java Script')) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reverseString(str){ | |
let newStr = ''; | |
for (let i = str.length-1; i >= 0; i--){ | |
newStr += str[i] | |
} | |
return newStr | |
} | |
console.log(reverseString('Java Script')) |