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!
MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does. Many developers create their classes as globals which is generally frowned up. I mostly disagree with that stance, but each to their own. In any event...
CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...
I've said it over and over but I'll say it again: JavaScript's main role in web applications is to enhance otherwise boring, static functionality provided by the browser. One perfect example of this is the Javascript/AJAX-powered star rating systems that have become popular over the...
I didn't realize that I truly was a nerd until I could admit to myself that ASCII art was better than the pieces Picasso, Monet, or Van Gogh could create. ASCII art is unmatched in its beauty, simplicity, and ... OK, well, I'm being ridiculous; ASCII...
The
.filter(Boolean)
part also sees the zeros as booleans and removes those numbers.very useful!