JavaScript 随机数 JavaScript随机数 Math.random() 返回0(包括)和1(不包括)之间的随机数: Math.random(); // 返回一个随机数字 复制尝试一下 Math.random() 始终返回低于1的数字。 JavaScript随机整数 用Math.random()与Math.floor()可以用于返回随机整数。 Math.floor(Math.random() * 10); // 返回 0 - 9 的随机整数 复制尝试一下 Math.floor(Math.random() * 11); // 返回 0 - 10 的随机整数 复制尝试一下 Math.floor(Math.random() * 100); // 返回 0 - 99 的随机整数 复制尝试一下 一个适当的随机函数 从上面的示例中可以看出,创建适当的随机函数以用于所有随机整数目的可能是个好主意。此JavaScript函数始终返回min(包含)和max(不包括)之间的随机数: function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min) ) + min; }复制尝试一下 此JavaScript函数始终返回min和max之间的随机数(包括两者): function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; }复制尝试一下