2

Like I have var arr = [1,2,3,4,5], I want this to become arr["1","2","3","4","5"]. I tried using:

var x = arr[0].toString(); //outputs "1"

but when I do typeof x it outputs "number".

How can I convert this that when I do typeof it will output "string"?

Mark Walters
  • 12,060
  • 6
  • 33
  • 48

5 Answers5

4

Most elegant solution

arr = arr.map(String);

This works for Boolean and Number as well. Quoting MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.

As for VisioNs answer, this only works for browser that support Array.prototype.map

Prinzhorn
  • 22,120
  • 7
  • 61
  • 65
3

One way is to use Array.prototype.map():

var arrOfStrings = arr.map(function(e) { return e + ""; });

Check the browser compatibility and use shim if needed.

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • I'd rather use the native [.toString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FNumber%2FtoString) method instead of constructing a string. – Simon May 31 '13 at 09:30
  • @Simon Why, if not a secret? – VisioN May 31 '13 at 09:31
  • Simply because it's more readable imho, you see what exactly is happening with the value. – Simon May 31 '13 at 09:33
  • Hm on the other hand your code is more bullet proof because it doesn't break if for some reason an array value should be `null` or `undefined`... – Simon May 31 '13 at 09:37
  • @Simon indeed, combining `null` or `undefined` with a blank string will convert it to a string. – Mark Walters May 31 '13 at 09:44
  • Post this as an answer @Prinzhorn, probably the most elegant way to handle the task. – Simon May 31 '13 at 09:50
1

Probably a more elegant way of doing this but you could loop the array and convert each value to a string by adding it to a blank string +="". Check here for javascript type conversions

var arr = [1, 2, 3, 4];
for(var i=0;i<arr.length;i++) arr[i]+="";
alert(typeof arr[0]) //String
Community
  • 1
  • 1
Mark Walters
  • 12,060
  • 6
  • 33
  • 48
1

You can also use:

arr.join().split(',');
Hugo Mallet
  • 533
  • 5
  • 8
0

You can do it like this too: LIVE DEMO (if you want to use .toString())

var arr = [1, 2, 3, 4];

var i = 0;
arr.forEach(function(val) {
    arr[i] = val.toString();
    console.log(typeof(arr[i]));
    i++;
});
Siamak Motlagh
  • 5,028
  • 7
  • 41
  • 65