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".
A string is an object of type String whose value is text.
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings.
However, JavaScript strings are considered a primitive datatype, which means they are not objects.
The key difference between Array and String is that an Array is a data structure that holds a collection of elements having the same data types, while a String is a collection of characters.
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`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With