4

我在 Double bitwise NOT (~~) 上发现了以下简短而棘手的代码

- James Padolsey
http://james.padolsey.com/javascript/double-bitwise-not/

Web Reflection: JavaScript 中的两个简单技巧(旧的,但总是有用)
http://webreflection.blogspot.com/2008/06/two-simple-tricks-in-javascript-olds.html


双位不

Math.round(v)=== ~~v

Math.floor(v)=== ~~v(如果 v > 0)

isNaN(Number(v)) ? 0 : Number(v)=== ~~v(如果 v is not float)


double not

Boolean(v)=== !!v

( !Boolean(v)=== !v)

bitwise shift

Math.round(v / 2)=== v >> 1

Math.round(v)=== v >> 0


single bitwise not

a.indexOf(v) !== -1=== ~a.indexOf(v)


javascript中有更多简短或棘手的代码吗?

4

1 回答 1

4

这些“技巧”并非特定于 Javascript。在 Google 上进行简单搜索将返回许多提供类似技巧的页面。

http://resnet.uoregon.edu/~gurney_j/jmpc/bitwise.html

http://lab.polygonal.de/2007/05/10/bitwise-gems-fast-integer-math/

http://www.beyond3d.com/content/articles/8/

于 2011-05-23T03:41:33.460 回答