JavaScript Tip: Cast a Whole Array to a Different Type
As in every dynamic language, a JavaScript’s variable type is declared by its content (a variant). Types are still important because 4+5 isn’t like “4”+”5” or “4”+5. There are several ways to convert a String into a Number:
1 2 3 4 5 | |
Assuming you have an array of strings, which their content is a number:
1
| |
and you want to cast all items to real numbers:
The Long Way
1 2 3 4 | |
A Shorter Way
Using JavaScript’s new native Array#map method, or any self-respecting JS Framework’s map function (MooTools’ Array.map, jQuery’s $.map), you can simply do:
1 2 3 4 5 | |
The arr.map(Number) simply runs over all items in array, executes the Number function on every item and adds the result into a new array. Just like as shown in the previous example.
On the same basis, you can convert to String, Date, RegExp. However, not a Boolean, since Boolean(“false”) is true.