diff --git a/_posts/zh_CN/2016-01-18-rounding-the-fast-way.md b/_posts/zh_CN/2016-01-18-rounding-the-fast-way.md index 8c507a3e..4ad669d3 100644 --- a/_posts/zh_CN/2016-01-18-rounding-the-fast-way.md +++ b/_posts/zh_CN/2016-01-18-rounding-the-fast-way.md @@ -54,20 +54,25 @@ For a solo programmer, that psychopath is inevitably "you in six months".(这 ##### 当处理大数时 因为`~`首先将数组转换为32位,`~~`的结果伪值在 ±2.15*10^12左右。如果你没有明确的检查输入值的范围,当转换的值最终与原始值有很大差距时,用户就可能触发未知的行为: + ```js a = 2147483647.123 // 比32位最大正数,再多一点 console.log(~~a) // -> 2147483647 (ok) a += 10000 // -> 2147493647.123 (ok) console.log(~~a) // -> -2147483648 (huh?) ``` + 一个特别容易中招的地方是在处理Unix时间戳时(从1970年1月1日 00:00:00 UTC开始以秒测量)。一个快速获取的方法: + ```js epoch_int = ~~(+new Date() / 1000) // Date() 以毫秒计量,所以我们缩小它 ``` + 然而,当处理2038年1月19日 03:14:07 UTC 之后的时间戳时(有时称为**Y2038 limit**), 可怕的事情发生了: + ```js // 2040年1月1日 00:00:00.123 UTC的时间戳 -epoch = +new Date('2040-01-01') / 1000 + 0.123 // -> 2208988800.123 +epoch = +new Date('2040-01-01') / 1000 + 0.123 // -> 2208988800.123 // 回到未来! epoch_int = ~~epoch // -> -2085978496 @@ -80,11 +85,13 @@ console.log(new Date(epoch_flr * 1000)) // -> Sun Jan 01 2040 00:00 ##### 当原始输入的数据类型不确定时 因为`~~`可以将任何非数字类型转换为`0`: + ```js console.log(~~[]) // -> 0 console.log(~~NaN) // -> 0 console.log(~~null) // -> 0 ``` + 一些程序员将其看作适当输入验证的替代品。然而,这将导致奇怪的逻辑问题,因此你不能辨别违法输入还是真正的`0`。因此这_并不_推荐。 ##### 当很多人认为`~~X == Math.floor(X)`时