在js中,生成1到10之间的随机整数有很多种方法,本文将介绍其中的一种方法,即使用Math.random()方法。Math.random() 方法可以返回 0 ~ 1 之间的随机数,可以用来生成1到10之间的随机整数。具体的实现方法如下:
使用Math.random()
Math.random() 方法可以返回 0 ~ 1 之间的随机数,可以用来生成1到10之间的随机整数。具体的实现方法如下:
// 获取1到10之间的随机整数 function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min) } // 使用 let num = getRandomInt(1, 10) console.log(num)
上面的代码中,我们使用了Math.random()方法来生成1到10之间的随机整数,并将其保存在变量num中。我们可以使用console.log()方法来查看num的值,以确保它是一个1到10之间的随机整数。
使用Math.floor()
Math.floor()方法可以返回小于或等于给定数字的最大整数,可以用来生成1到10之间的随机整数。具体的实现方法如下:
// 获取1到10之间的随机整数 function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min } // 使用 let num = getRandomInt(1, 10) console.log(num)
上面的代码中,我们使用了Math.floor()方法来生成1到10之间的随机整数,并将其保存在变量num中。我们可以使用console.log()方法来查看num的值,以确保它是一个1到10之间的随机整数。
使用Math.random()和Math.floor()方法可以很容易地生成1到10之间的随机整数。它们的实现方法都很简单,而且可以用来生成任意范围内的随机整数。