使用JavaScript数组进行类型转换

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!

验证可能而且应该更加严格,但是通过类型转换进行的基本验证可能会对您有所帮助!

翻译自: https://davidwalsh.name/javascript-array-typecast

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值