5
var nice = new String("ASH");
nice; //String {0: "A", 1: "S", 2: "H", length: 3, [[PrimitiveValue]]: "ASH"}
var reverseNice = Array.prototype.reverse.call(nice);
reverseNice.toString(); // "ASH"

whereas I was expecting reverseNice to be "HSA".

2
  • new String() will return only string object not primitive string. For that use "". Commented Apr 18, 2015 at 3:52
  • 1
    @hitman4890 it gives you something closer to how JavaScript treats all Strings internally (which is why we can access properties on them even though they're primitive values) Commented Apr 18, 2015 at 3:55

3 Answers 3

8

You can't make changes to nice, try it;

nice[0] = 'f';
nice[0]; // "A"

If you wanted to use the Array method, convert it to a true Array first

var reverseNice = Array.prototype.slice.call(nice).reverse(); // notice slice
reverseNice.join(''); // "HSA", notice `.join` not `.toString`
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, JavaScript strings are immutable. Also note that new String() returns an object, and String() returns a primitive type.
0

Why not do this?

var nice = "ASH".split("");
nice; //Array {0: "A", 1: "S", 2: "H", length: 3}
var reverseNice = nice.reverse();
reverseNice.join("").toString(); // "HSA"

or just

var nice = "ASH".split("");
var reverseNice = nice.reverse().join("").toString();

1 Comment

If you use split() then this returns an Array object itself. Therefore you don't need Array.prototype.reverse.call(nice);. You just need var reverseNice = nice.reverse(). You also don't need toString() after the join, since join returns a string.
0

use the split and join to convert type from string to array , just like this .

var nice = new String("ASH");
// create a string 


var result = Array.prototype.reverse.call(nice.split('')).join('');
// string can not use the reverse, 
// so we need split it and call the prototype function of Array ,
// and join the result in the end 

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.