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!
This is the hardest thing I've ever had to write, much less admit to myself. I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life. All of those feelings were very...
Back in late 2012 it was not easy to find open source projects using requestAnimationFrame()
- this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...
Cocoon
I love canvas, I love interactive demos and I don't think I have ever been more impressed by somebody's work than when I discovered what Tiffany Rayside has created on CodePen. So I had to start off with one of her interactive canvas pens, even though...
Counters. They were a staple of the Geocities / early web scene that many of us "older" developers grew up with; a feature then, the butt of web jokes now. CSS has implemented its own type of counter, one more sane and straight-forward than the ole...
The
.filter(Boolean)
part also sees the zeros as booleans and removes those numbers.very useful!