Type Conversion with JavaScript Arrays
JavaScript's loose nature allows developers to employ amazing tricks to do just about anything you'd like. I've detailed how you can filter falsy values in arrays using a filter(Boolean)
trick, but reader David Hibshman shared another trick for typecasting array values the same way.
To typecast an array of elements, you can use map
and the desired return type:
["1", "9", "-9", "0.003", "yes"].map(Number);
// [1, 9, -9, 0.003, NaN]
I love this trick but you could argue the code itself could be considered confusing, so wrapping it a helper function would be helpful:
function arrToNumber(arr) {
return arr.map(Number).filter(Boolean);
}
Validation could and should probably be more rigorous but basic validation through typecasting might help you!
![9 Mind-Blowing Canvas Demos]()
The <canvas>
element has been a revelation for the visual experts among our ranks. Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead. Here are nine unbelievable canvas demos that...
![Facebook Open Graph META Tags]()
It's no secret that Facebook has become a major traffic driver for all types of websites. Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly. And of course there are Facebook "Like" and "Recommend" widgets on every website. One...
![9 Incredible CodePen Demos]()
CodePen is a treasure trove of incredible demos harnessing the power of client side languages. The client side is always limited by what browsers provide us but the creativity and cleverness of developers always pushes the boundaries of what we think the front end can do. Thanks to CSS...
![MooTools 1.2 OpenLinks Plugin]()
I often incorporate tools into my customers' websites that allow them to have some control over the content on their website. When doing so, I offer some tips to my clients to help them keep their website in good shape. One of the tips...
The
.filter(Boolean)
part also sees the zeros as booleans and removes those numbers.very useful!