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

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

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.

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

Comments

1

You can also use:

arr.join().split(',');

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++;
});

Comments

Your Answer

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.