我们可以用 ~ 替换 Math.floor 并仍然得到相同的结果吗?

Can we replace Math.floor by ~ and still get the same result?

我看到通过替换这行代码

Math.floor(Math.random() * 10) 

来自这个:

~(Math.random() * 10

我得到了相同的结果,这是为什么?

是的,您可以:

parseInt(yourvalue)

简短的回答是否定的,它是语法,因此您必须输入一些内容才能将浮点数舍入为整数。

Math.floor() 或 parseInt()。

如果您想自己缩短输入时间,您可以创建一个短命名函数,returns 结果相同:

function mf(number){
  return Math.floor(number);
}

console.log(mf(Math.random() * 10));

,因为它们的工作方式不同。 ~ NOT 运算符反转整数的位,因此如果您有二进制数 0101(十进制为 5),运算符将 return:

~0101 = 1010;  // ~5 = 10

但由于 JavaScript 使用 32 位有符号整数,结果会有所不同:

~00000000000000000000000000000101 = 11111111111111111111111111111010  // ~5 = -6

Math.floor() 函数 return 是小于或等于一个数的最大整数,因此使用与数字 5 相同的示例:

Math.floor(5) // ==> would return 5

您可以看到两个运算符 return 不同的值。 但是,可以使用浮点数中的 ~ 运算符模拟 Math.Floor() 函数,只需将数字乘以 * -1 然后将结果减去 - 1,但是 我几乎不推荐它 因为它使代码更难辨认:

const number = 5.56;

console.log(~number  * -1 - 1);    // returns 5

console.log(Math.floor(number));  // returns 5

总而言之,它们是不同的运算符,它们各有各的功能。