Reverse a string using the unshift() method in JavaScript.
Code:
let sentence="Hello, my name is John Doe. I am a software developer.";
let reversedSentence=[] ;
for(let char of sentence){
reversedSentence.unshift(char);
}
console.log(reversedSentence.join(''));
Output:
.repoleved erawtfos a ma I .eoD nhoJ si eman ym ,olleH
Explanation:
1. We start with a string `sentence` that we want to reverse.
2. We create an empty array `reversedSentence` to hold the characters in reverse order.
3. We use a for...of loop to iterate over each character in the `sentence`.
4. Inside the loop, we use the `unshift()` method to add each character to the beginning
of the `reversedSentence` array.
5. Finally, we use the `join('')` method to convert the array back into a string and print
it to the console.
No comments:
Post a Comment