I've searched here: .asp but could not find any convenience method to perform this function. If I have an array var arrayOfStrings = ["20","10","30","100"]
, is there a quick way to remove all quotes (") from each string in this array without having to loop through?
I essentially want to create this: var arrayOfNumbers = [20,10,30,100]
Thanks
I've searched here: http://w3schools.com/jsref/default.asp but could not find any convenience method to perform this function. If I have an array var arrayOfStrings = ["20","10","30","100"]
, is there a quick way to remove all quotes (") from each string in this array without having to loop through?
I essentially want to create this: var arrayOfNumbers = [20,10,30,100]
Thanks
Share Improve this question asked Aug 2, 2012 at 17:07 ApolloApollo 9,05433 gold badges110 silver badges193 bronze badges 3- Do you want to convert your strings into integers ? – Bali Balo Commented Aug 2, 2012 at 17:09
- @BaliBalo edited to be more clear. thanks – Apollo Commented Aug 2, 2012 at 17:10
- Use MDN docs, w3c is aweful: w3fools.com – Jasper Commented Aug 5, 2012 at 16:57
4 Answers
Reset to default 17If you want number conversion, you can do it like this...
var arrayOfNumbers = arrayOfStrings.map(Number);
The .map()
method creates a new array populated with the return value of the function you provide.
Since the built-in Number
function takes the first argument given and converts it to a primitive number, it's very usable as the callback for .map()
. Note that it will interpret hexadecimal notation as a valid number.
Another built-in function that would accomplish the same thing as the callback is parseFloat
.
var arrayOfNumbers = arrayOfStrings.map(parseFloat)
The parseInt
function however will not work since .map()
also passes the current index of each member to the callback, and parseInt
will try to use that number as the radix parameter.
- MDN Array.prototype.map (includes compatibility patch)
DEMO: http://jsfiddle.net/UDWvH/
[
20,
10,
30,
100
]
You could try like this:
for(var i = 0; i < myArray.length; i++)
{
myArray[i] = parseInt(myArray[i], 10);
}
Have a look to the parseInt function.
For browsers that support JSON.parse:
var arr = ["20","10","30","100"];
var newArr = JSON.parse("[" + arr.join() + "]");
console.log(typeof arr[0]); //string
console.log(typeof newArr[0]); //number
You do not need to do anything, the double quotes in JavaScript are identifiers that state that the data within them is a string. This means they are not part of the array or data itself.
You can loop using a standard For loop.