0
  • I am new to js.
  • I am trying to write a code which reverses null terminated string.
  • I tried writing using push and pop.
  • but i am not getting output, can you tell me what is the problem.
  • providing code below
var word = "Cell0";
//var char = word.stringCharAT();


for (i=0;  i< word.length; i++) {
    var pushWord = [];

    pushWord.push(word[i]);

    for (j=0;  j< pushWord.length; j++) {
        var reverseWord= [];
        reverseWord = pushWord[j].pop;
        console.log("reverseWord" + reverseWord);

    } 
}

3 Answers3

0

Here's a solution.

var word = "Cell0"; 
var reversed = ''; 
for (var i = word.length-1; i >= 0; i--) {
    reversed += word[i];
} 
console.log(reversed);

This loops through the characters of the string in reverse and adds the characters to a new string.

heylookltsme
  • 124
  • 6
0

pushWord[j] is not an array, .pop is not called.

Define pushWord and reverseWord arrays outside of for loop, within loop, after word[i] is pushed to pushWord, call .unshift() on reverseWord with pushWord[pushWord.length -1] as parameter.

var word = "Cell0";
var pushWord = [];
var reverseWord = [];
for (let i = 0; i < word.length; i++) {
  pushWord.push(word[i]);
  reverseWord.unshift(pushWord[pushWord.length - 1]);
}
console.log("reverseWord" + reverseWord);
guest271314
  • 1
  • 15
  • 104
  • 177
0

var originalWord = "Cell0";
var reverseWord = [];
for (let i = 0; i < originalWord.length; i++) {
  reverseWord.unshift(originalWord [i]);
}
console.log(reverseWord.join(''));

You don't even need to push. Another way to achieve the result!

Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18