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.4k6 gold badges36 silver badges48 bronze badges
asked May 31, 2013 at 9:26

5 Answers 5

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

answered May 31, 2013 at 9:51
Sign up to request clarification or add additional context in comments.

Comments

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.

answered May 31, 2013 at 9:28

6 Comments

I'd rather use the native .toString() method instead of constructing a string.
@Simon Why, if not a secret?
Simply because it's more readable imho, you see what exactly is happening with the value.
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 indeed, combining null or undefined with a blank string will convert it to a string.
|
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
answered May 31, 2013 at 9:32

Comments

1

You can also use:

arr.join().split(',');
answered May 31, 2013 at 11:11

Comments

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++;
});
answered May 31, 2013 at 9:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.