[ 问题描述 ]
在网上看到了两种设置随机颜色的取值代码。但不知道"~~"是干什么用的?
var a = (~~(Math.random() * 255)); //"~~"是什么运算符?
var b = Math.floor((Math.random() * 255));
[ 符号用法 ]
首先,颜色rgb值的三个参数都是0~255的整数。而~~
和Math.floor()
的作用都是将小数转化为整数。但是对于负数它们的运算结果会有一些不同。
Math.floor()
方法:将数字向下舍入到最接近的整数,并返回结果。如果传递的参数是整数,则该值不会被舍入。~~
两个按位非操作符,作用是干掉数字的小数部分。和强制类型转换的结果基本一样。
若想获得更好的可读性,使用Math.floor。若想最小化它,使用波浪号~~ 。
~(5.5) // => -6
~(-6) // => 5
~~5.5 // => 5 (same as Math.trunc(5.5) and Math.floor(5.5))
~~(-5.5) // => -5 (same as Math.trunc(-5.5) but NOT the same as Math.floor(-5.5), which would give -6 )
<script>
//Math.floor(): 该方法将数字向下舍入到最接近的整数,并返回结果。如果传递的参数是整数,则该值不会被舍入。
console.log( Math.floor( 8.0), Math.floor( 8.4), Math.floor( 8.5), Math.floor(