ashwinik001
ashwinik001

Reputation: 5163

new String() does not behave like an array like object

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

Answers (3)

qianjiahao
qianjiahao

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

James Wilkins
James Wilkins

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

Paul S.
Paul S.

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

Related Questions