引入
在大多数情况下,他们都可以用来取一个小数的整数部分,但是在某些特殊场景下,就只能使用math.floor。比如我们想取一个区间范围内的值,如果使用…,就可以取到…,但如果使用…,就只能取到。这是为什么呢?首先我们还是从他们的原理开始看。
console.log(Math.floor(4.95)); // 4
console.log(Math.floor(4.5)); // 4
console.log(Math.floor(4.05)); // 4
console.log(Math.floor(-4.05)); // -5
区别
Math.floor 它只是简单地将一个数向下取整到最接近的整数。
它只接受一个参数:你想要向下取整的数。
console.log(Math.floor(4.95)); // 4
console.log(Math.floor(4.5)); // 4
console.log(Math.floor(4.05)); // 4
console.log(Math.floor(-4.05)); // -5
parseInt在处理负数时不会向下取整:
console.log(Math.floor(-4.05)); // -5
console.log(parseInt('-4.05')); // -4
parseInt会忽略任何数字后面的非数字字符:
console.log(parseInt('4.05abc')); // 4
console.log(Math.floor('4.05abc')); // NaN
parseInt也可以用来在不同的基数中解析字符串:
console.log(parseInt('11', 2)); // 3 在2进制中,11表示的是十进制中的3
场景
我们再看到最开始的例子,如果我们想实现一个函数,能够获取 -2 到 -1之间的随机数(包括 -2 和 -1)那么应该怎么做呢?
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(randomRange(-2, -1));
首先,它为什么能获取 -2 到 -1之间的随机数呢?
(max - min)的值是 1,Math.random()的返回值是 [0,1)
所以 Math.random()*(max - min)
的范围值 [0,1)
Math.random() * (max - min) + min
的范围是 [-2,-1)
很多同学可能会发现,永远取不到 -1?因为 Math.floor
永远是向下取整。
如果我们修改为以下样子:
(max + 1 - min)的值是 2, Math.random()*(max + 1 - min)的范围值 [0,2)
Math.random() * (max + 1 - min) + min 的范围是 [-2,0)。
其中,-2,-1.5 一直到-1,都会取-2。而 -1,-0.5一直到0,都会取-1。
====================================
function randomRange(min, max) {
return parseInt(Math.random() * (max + 1 - min) + min);
}
(max - min)的值是 1,Math.random()*(max - min)的范围值 [0,1)
Math.random() * (max - min) + min 的范围是 [-2,-1) 永远是 -1,取不到-2。
(max + 1 - min)的值是 2, Math.random()*(max + 1 - min)的范围值 [0,2)
Math.random() * (max + 1 - min) + min 的范围是 [-2,0)。
我们仍然取不到-2,因为 -1.9 -1.8 -1.7都会取 -1 ,-0.9,-0.8都会取0,所以它会在 -1 和 0之间随机取