2022 IT鐵人賽 - [ Day 2 ] [ JS ] 產生大小寫字母、隨機字母、隨機 6 位密碼

Daisy
3 min readSep 16, 2022

今天想跟大家分享的是基礎的 JavaScript,會複習到 String 的一些方法。

String Methods

String.fromCharCode()

  • 作用:把 UTF-16 轉換成字符
  • 語法:String.fromCharCode(n1, n2, …, nX)
  • 回傳值:字符 (string type)
let char = String.fromCharCode(65)
console.log(char) // A

String.fromCodePoint()

  • 與 String.fromCharCode() 作用一樣,不同的是編碼為 Unicode
  • 無效則拋出 RangeError

charCodeAt()

  • 作用:把字串中指定的字符(用 index 表示)轉換成 UTF-16 code
  • 語法:string.charCodeAt(index)
  • index 若不是數字,會預設為 0
  • 回傳值:UTF-16 (0 ~ 65535)(number type),如果 index 無效則回傳 NaN
let texts = ‘How are you?’
let charCode = texts.charCodeAt(1)
console.log(charCode) // 111

codePointAt()

  • 與 charCodeAt() 作用一樣,不同的是編碼為 Unicode
  • 無效則回傳 undefined

今天的題目有三個,程式碼是連續的

Q1.

產生 26 個大小寫字母

Sol.

const upperChars = []
const lowerChars = []
// A ~ Z 的編碼是 65 ~ 90
for (let i = 65; i < 91; i++) {
let char = String.fromCharCode(i)
upperChars.push(char)
lowerChars.push(char.toLowerCase())
}

結果

Q2.

產生隨機字母

Sol.

// 先合併大小寫字母
const arr = upperChars.concat(lowerChars)
let randomChar = arr[Math.floor(Math.random() * 52)]
console.log(randomChar) // A (隨機)

Q3.

隨機產生 6 位密碼

Sol.

// 先產生數字 0 ~ 9
const nums = []
for (let i = 0; i <= 9; i++) {
nums.push(i)
}
// 合併大小寫字母與數字
const arr = upperChars.concat(lowerChars, nums)
const sixCodes = []

for (let i = 1; i <= 6; i++) {
let randomCode = arr[Math.floor(Math.random() * 62)]
sixCodes.push(randomCode)
}
console.log(sixCodes.join(‘’)) // o748YK (隨機)

Demo

> 參考資料:
MDN String.fromCharCode()String.fromCodePoint()charCodeAt()codePointAt()
> 文章同步更新於 2022 IT鐵人賽

--

--