gpt4 book ai didi

javascript - MDN 示例(Math.random()): could it be parseInt() instead of Math. Floor()?

转载 作者:行者123 更新时间:2023-11-28 19:03:58 26 4
gpt4 key购买 nike

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

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

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

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

相反?我在写这个问题时想到,当 4,5 时,Math.floor() 可能会写出 5,而 parseInt() 会写出 4,但这对于随机来说并不重要据我了解,数字生成器(如果您知道什么时候它很重要的任何示例,请告诉我!)那么,在这种情况下仍然没有太大区别?

最佳答案

parseInt字符串解析为整数,仅读取该字符串开头的数字。使用将数字舍入为整数是不合适的。数字会先转换为字符串,有时会产生意想不到的结果:

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

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 始终向下舍入。

关于javascript - MDN 示例(Math.random()): could it be parseInt() instead of Math. Floor()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32039288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com