随机数是编程语言中的重要组成部分。在JavaScript中,生成随机数是一项简单的任务。本文将介绍生成随机数的各种方法。
生成范围随机数
function random(min, max) {
return Math.floor(min + Math.random() * ((max + 1) - min))
};
生成随机字符串
function randomStr(length) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
生成随机颜色
function randomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}