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.
JavaScript的松散性质使开发人员可以采用惊人的技巧来完成您想要的任何事情。 我已经详细说明了如何使用filter(Boolean)
技巧filter(Boolean)
数组中的伪造值 ,但是读者David Hibshman分享了另一个技巧,以相同的方式类型化数组值。
To typecast an array of elements, you can use map
and the desired return type:
要强制转换元素数组,可以使用map
和所需的返回类型:
["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!
验证可能而且应该更加严格,但是通过类型转换进行的基本验证可能会对您有所帮助!