¸üÐÂʱ¼ä:2021Äê11ÔÂ16ÈÕ16ʱ42·Ö À´Ô´:ÀÖÓãµç¾º ä¯ÀÀ´ÎÊý:
Math.random()ÓÃÀ´»ñÈ¡Ëæ»úÊý£¬Ã¿´Îµ÷Óø÷½·¨·µ»ØµÄ½á¹û¶¼²»Í¬¡£¸Ã·½·¨·µ»ØµÄ½á¹ûÊÇÒ»¸öºÜ³¤µÄ¸¡µãÊý£¬Èç“0.925045617789475"£¬Æä·¶Î§ÊÇ0~1(²»°üÀ¨1)¡£
ÓÉÓÚMath.random()·µ»ØµÄÕâ¸öËæ»úÊý²»Ì«³£Óã¬ÎÒÃÇ¿ÉÒÔ½èÖúһЩÊýѧ¹«Ê½À´×ª»»³ÉÈÎÒⷶΧÄÚµÄËæ»úÊý£¬¹«Ê½Îª“Math.random()*(max - min) + min"£¬±íʾÉú³É´óÓÚ»òµÈÓÚminÇÒСÓÚmaxµÄËæ»úÖµ¡£Ê¾Àý´úÂëÈçÏ¡£
Math.random()*(3 - 1) + 1; // 1≤·µ»Ø½á¹û<3 Math.random()*(20 - 10) + 10; // 10≤·µ»Ø½á¹û<20 Math.random()*(99 - 88) + 88; // 88≤·µ»Ø½á¹û<99
ÉÏÊö´úÂëµÄ·µ»Ø½á¹ûÊǸ¡µãÊý£¬µ±ÐèÒª»ñÈ¡ÕûÊý½á¹ûʱ£¬¿ÉÒÔ´îÅäMath.floor()À´ÊµÏÖ¡£ÏÂÃæÎÒÃÇͨ¹ý´úÂëÑÝʾÈçºÎ»ñÈ¡1~3·¶Î§ÄÚµÄËæ»úÕûÊý£¬·µ»Ø½á¹û¿ÉÄÜÊÇ1¡¢2»ò3¡£
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
console. log(getRandom(1, 3)); //×îСֵ1£¬×î´óÖµ3
ÉÏÊö´úÂëÖУ¬µÚ2ÐÐÓÃÀ´Éú³Éminµ½maxÖ®¼äµÄËæ»úÕûÊý£¬°üº¬minºÍmax¡£ÁíÍ⣬¹ý¿ÉÒÔʹÓÃMath.floor(Math.random() * (max + 1))±íʾÉú³É0µ½maxÖ®¼äµÄËæ»úÕûÊý£¬Ê¹ÓÃMath.floor(Math.random() * (max + 1)+ 1)±íʾÉú³É1µ½maxÖ®¼äµÄËæ»úÕûÊý¡£
ÀûÓÃËæ»úÊý£¬¿ÉÒÔʵÏÖÔÚÊý×éÖÐËæ»ú»ñȡһһ¸öÔªËØ£¬Ê¾Àý´úÂëÈçÏ¡£
var arr = ['apple', 'banana', 'orange', 'pear']; //µ÷ÓÃÇ°Ãæ±àдµÄgetRandom()ÀöÊý»ñÈ¡Ëæ»úÊý console.log(arr[getRandom(0, arr.length - 1)]);
±±¾©Ð£Çø