方法一
步驟構思:Math物件隨機,轉16進制字符,截取六位字符
var a = Math.random(); // 呼叫靜態物件方法拋出亂數a
console.log(a);
var b = a.toString(16); // 把a轉換為16進制的字串
console.log(b);
console.log(b.length); // 15
/* 進制的問題,為什么不是16(就像十進制為什么只有9而沒有10) */
var c = b.substr(-6); // 截取字串后六位
console.log(c);
var color = '#' + Math.random().toString(16).substr(-6); // 加上'#'串聯成一行代碼
console.log(color);
方法二
步驟構思:陣列遍歷六次,Math物件隨機索引,共存盤六位字符
var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
console.log(arr.length); // 16
function getColor() {
var str = '#';
for (var i = 1; i <= 6; i++) {
function getRandom(min, max) { // 呼叫靜態物件Math.random(包含大小值間取一個整數)
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var num = arr[getRandom(0, arr.length - 1)]; // 把從陣列中隨機索引的一個字串賦值給變數
/* 十六進制的長度為何要-1(就像十進制為什么只有9而沒有10),如果超出則報underfined */
str += num;
}
return str; //遍歷索引滿6個字符則回傳函式值
}
var color = getColor();
console.log(color.toLowerCase()); // 把字串轉為小寫輸出
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/109125.html
標籤:JavaScript
上一篇:用原生JS寫16進制隨機顏色
