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"?
5 Answers 5
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
Comments
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.
6 Comments
null or undefined...null or undefined with a blank string will convert it to a string.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
Comments
You can also use:
arr.join().split(',');
Comments
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++;
});