Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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".

like image 641
dopeddude Avatar asked Apr 18 '15 03:04

dopeddude


People also ask

Is String not an object?

A string is an object of type String whose value is text.

Is a String an object?

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.

Is String considered as object in JS?

However, JavaScript strings are considered a primitive datatype, which means they are not objects.

How does a String differ from an integer array?

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.


1 Answers

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`
like image 68
Paul S. Avatar answered Sep 30 '22 00:09

Paul S.