Reputation: 5163
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".
Upvotes: 5
Views: 208
Reputation: 399
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)
Upvotes: 0
Reputation: 7367
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();
Upvotes: 0
Reputation: 66324
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`
Upvotes: 8