JavaScript ASCII 轉換字元及 Math.random 對應
隨機亂數方法 Math.random() 在規定範圍的兩個數字之間生成一個隨機選取的 Random Value 隨機數。
JavaScript 處理字元時,需要和 ASCII 碼與字元相互轉換,傳回字串中的十進位 ASCII 編碼、或 ASCII 碼轉換成基本字串。
charCodeAt()
傳回字串中「一個字」的十進位的 ASCII 編碼。返回 0 到 65535 之間的整數。
var str = "ABC";
console.log(str.charCodeAt()); // 65
console.log(str.charCodeAt(0)); // 65
console.log(str.charCodeAt(1)); // 66
console.log(str.charCodeAt(2)); // 67
var str = "字串";
console.log(str.charCodeAt(0)); // 23383
console.log(str.charCodeAt(1)); // 20018
console.log(str.charCodeAt(2)); // NaN
fromCharCode()
返回 Unicode, UTF-16 或 ASCII 碼轉換成基本字串。UTF-16 代碼單元的數字。範圍介於 0 到 65535(0xFFFF)之間。
String.fromCharCode(65); // 'A'
String.fromCharCode(65, 66, 67); // 'ABC'
String.fromCharCode(0x5B57, 0x4E32); // '字串'
23383 十六進位 = 5B57 、 20018 十六進位 = 4E32
console.log("\u5B57\u4E32"); // '字串'
因為 fromCharCode() 僅適用於十六進位值(與 \u 轉義序列相同)所以需要代理對才能返回補充字符。
於 Math.random 對應
Math.random() 非真亂數值,傳回非真亂數值,數值大於等於 0 小於 1。亂數方法用電腦的當下「時間為種子」。
var n1 = Math.random();
var n2 = parseInt(n1 * 100);
console.log(n1);
console.log(n2);
n1 = .
n2 = .
n2 = .
使用 Math.random 對應 ASCII 碼產生 100 個字元,為方便驗證結果可以使用 以排序輸出。
為排序所以先用 Array 陣列儲存亂數,再顯示出產生的結果。
for (var i = 0; i < 100; i++) {
var result = (Math.floor(Math.random() * 10));
a.push(String.fromCharCode(result + 48));
}
for (var i = 0; i < 100; i++) {
var result = (Math.floor(Math.random() * 26));
a.push(String.fromCharCode(result + 65));
}
for (var i = 0; i < 100; i++) {
var result = (Math.floor(Math.random() * 26));
a.push(String.fromCharCode(result + 97));
}