MDN示例(Math.random()):可以是parseInt()而不是Math.floor()吗? [英] MDN example (of Math.random()): could it be parseInt() instead of Math.floor()?

查看:264
本文介绍了MDN示例(Math.random()):可以是parseInt()而不是Math.floor()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我偶然发现Math.random()的示例时,我正在阅读JavaScript教程并在MDN网站上搜索函数:

I was reading a JavaScript tutorial and searching for functions on MDN website when I stumbled across this example of Math.random():

function getRandomIntInclusive(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

虽然我知道Math.floor选择了最大的数字,并且删除了所有具有十进制值的数字,但我已经学到了另一个名为parseInt()的函数,该函数仅删除点后的所有数字.那么,这两者之间有什么区别?我不能只是使用

While I understand that Math.floor chooses the biggest number and with that erases all numbers that have decimal values, I already learnt another function called parseInt() which just deletes all of the numbers after point. So, what's the difference between those two? Couldn't I just use

function getRandomInclusive(min, max) {
return parseInt(Math.random() * (max - min + 1)) + min;
}

而不是? 我在写这个问题时就知道Math.floor()在4,5时可能会写5,而parseInt()会写4,但是据我所知,这对于随机数生成器并不是很重要(如果您知道何时出现重要,请告诉我!)因此,在这种情况下仍然没有太大区别吗?

instead? I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4, but it's not really important for random number generator as I understand (if you know any examples of when it would be important, please tell me!) So, there's still not much of a difference in this case?

推荐答案

parseInt字符串解析为整数,仅读取该字符串开头的数字.将数字四舍五入为整数是不合适的.该数字将首先转换为字符串,有时会产生意外结果:

parseInt parses a string into an integer, reading only digits at the beginning of that string. It is not appropriate to use to round a number to an integer. The number will be converted to a string first, sometimes with unexpected results:

var num = 1000000000000000000000;
parseInt(num) // 1, because the string representation is 1e+21

我在写这个问题时有一个主意,即Math.floor()在4,5时可能会写5,而parseInt()在4时会写

I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4

您正在考虑四舍五入到最接近的整数,这就是Math.round的作用. Math.floor总是四舍五入.

You’re thinking of rounding to the nearest whole number, which is what Math.round does. Math.floor always rounds down.

这篇关于MDN示例(Math.random()):可以是parseInt()而不是Math.floor()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆