JavaScript中的地板编号:~~ n,n | 0或Math.floor(n)? [英] Flooring numbers in JavaScript: ~~n, n|0 or Math.floor(n)?
问题描述
我最近发现了除了 Math.floor(n)
之外的一些其他方法来删除JavaScript中的小数部分数值,特别是双位NOT运算符 ~~ n
并执行按位或0 n | 0
。
I've recently discovered some other ways to remove the fractional part of numeric values in JavaScript other than Math.floor(n)
, specifically the double bitwise NOT operator ~~n
and performing a bitwise or with 0 n|0
.
我想知道这些方法之间有什么区别,以及推荐一种方法与另一种方法的不同情况。
I'd like to know what are the difference between these approaches and what the different scenarios are where one method is recommended over another.
推荐答案
向下一个看你的代码的人清楚并使用 Math.floor()
。
Be clear to the next person looking at your code and use Math.floor()
.
性能提升1%-40%并不值得,所以不要制作你的代码令人困惑,难以维护。
The performance gain of 1%-40% isn't really worth it, so don't make your code confusing and hard to maintain.
这篇关于JavaScript中的地板编号:~~ n,n | 0或Math.floor(n)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!