Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • First Reverse in JavaScript
    Why doesn't this work?
    function FirstReverse (str) {
        var result=" ";
        for(var i=0;  i<str.length; i++){
            result+=str.unshift(i);
        }
        return result;
    }
    Thanks ^-^
    mashadim posted this question on 12/2/15 | reverse, javascript
    Answers
  • +
  • 1
  • -
  • To display code include the following tags:
    function firstReverse(str) { 
    
      return str.split("").reverse().join("");
    }
    
  • +
  • 1
  • -
  • In addition, the individual characters in a javascript string can be identitfied by their position, with bracket notation (as if the string is an array of characters, as in C. For example, if str = 'now', str[1] === 'o'. Therefore, an alternate way to do the reverse (and I think preferable, because it does not relay so much on the magic of a built-in method such as reverse) woulc be:
    function reverse(str) {
        var res = "";
        var len = str.length - 1;
        for (var i = len; i >= 0; i--) {
            res += str[i];
        }
        return res;
    }
    
    This is similar in nature to your first effort, except it doesn't try to use the unshift() method, which is unnecessary in any event, as there is no need to destroy the original string to build up the reverse string.
  • +
  • 1
  • -
  • To display code include the following tags:
    function FirstReverse(z) {
    	if (typeof z != String) {z += ''}
    	var ar = [], ra = [], i = 0;
    	while (i < z.length) {
    	  ar.push(z.substr(i++,1) );
    	}
    	for (i in ar) {
    	  ra.unshift(ar[i]);
    	}
    	return String(ra.join('') );
    }
       
    // keep this function call here 
    FirstReverse(readline());
  • +
  • 0
  • -
  • What is the meaning of the " " to which the result is being assigned?
     var result=" ";
  • +
  • 0
  • -
  • Hi MHaledjian. I know how to solve this problem with methods. I wasn't asking for a new solution and my question was answered already. Thank you anyway.
  • +
  • 0
  • -
  • yeah you're right! What I should have done was split the string, which would turn it into an array, then unshift would work, then do join on that to make it a string again. Thanks for your input :)
  • +
  • 0
  • -
  • Maybe, because string doesn't have 'unshift' method
  • +
  • 0
  • -
  • return new StringBuilder(str).reverse().toString() 
    This is in Java. I have 2 test not passed.Any idea why?!
    Log in to write an answer.