Javascript 筆記

Updated date:Alpha Camp 2-1 S3

迴圈系列

whlie迴圈(while、do while)

while(條件式) {執行動作} // 若符合條件則執行,每次執行前檢查條件
do {執行動作} while(條件式) // 先執行再檢查條件,若符合則再執行一次直到不符合為止
應用:2-1 S1A5Q1週年慶摸彩 彩卷號碼產生並檢查有無重複

const ticketPool = [] function generateTicket() { let ticket = '' // do..while迴圈,先做再檢查號碼有沒有重複,號碼重複再跑一遍do do { // 前兩碼英文字符 for (let i = 0; i < letterNum; i++) { ticket += String.fromCharCode(Math.floor(Math.random() * 26) + 65) } // 後四碼數字字符 ticket += Math.floor(Math.random() * (Math.pow(10, numberNum))).toString().padStart(numberNum, '0') } while (ticketPool.includes(ticket)) // 紀錄並回傳彩卷號碼 ticketPool.push(ticket) return ticket } // for...of迴圈,players陣列裡的物件逐項加入彩卷號碼 for (let i of players) { i.number = generateTicket() }

for迴圈(for、for in、for of)

for (let i = 0; i < n; i++) {執行動作} // 太常用不解釋
for (let key in object) {執行動作} // 依物件的key逐項執行,陣列和字串也可用
for (let value of array) {執行動作} // 依陣列的值逐項執行,物件和字串不能用

let arr = [3, 5, 7] arr.foo = "hello" for (let i in arr) { console.log(i) // output: 0, 1, 2, foo } for (let i of arr) { console.log(i) // output: 3, 5, 7 } let obj = { a: 123, b: 456, c: 789 } for (let i in obj) { console.log(i) // output: a, b, c } let str = 'abcdefg' for (let i in str) { console.log(i) // output: 0, 1, 2, 3, 4, 5, 6 }

陣列可用的其他迴圈 (forEach、map、filter)

陣列.forEach(function):遍歷每個元素,可改變原陣列的值
ex: arr.forEach((元素,index,arr) => {執行動作})
陣列.map(function):遍歷每個元素,不改變原陣列,需指定新陣列接回傳的值
ex: let newArr = arr.map((元素,index,arr) => {執行動作})
陣列.filter(function):遍歷每個元素,不改變原陣列,需指定新陣列接回傳 true 時的值
ex: let newArr = arr.filter((元素,index,arr) => {條件})

let arr1 = [1, 2, 3, 4, 5] // forEach完可能會改變原陣列 let arr2 = [1, 2, 3, 4, 5] // map、filter不改變原陣列 // ForEach arr1.forEach((num, index) => { return arr1[index] = num * 2; }) console.log(arr1) // [2, 4, 6, 8, 10] // Map let arrMap = arr2.map(num => { return num * 2; }) console.log(arr2) // [1, 2, 3, 4, 5] console.log(arrMap) // [2, 4, 6, 8, 10] // Filter let arrFilter = arr2.filter(num => { return num > 2 }) console.log(arr2) // [1, 2, 3, 4, 5] console.log(arrFilter) // [3, 4, 5] // Map疊加Filter let arrMapFilter = arr2.map(num => num * 2).filter(num => num > 5) console.log(arrMapFilter) // [6, 8, 10]

Array 陣列

頭/尾 - 插入/刪除(shift/unshift、pop/push)

  • arr.shift()
  • arr.unshift(element1[, [, elementN]])
  • arr.pop()
  • arr.push(element1[, [, elementN]])
let arr = [0, 1, 2, 3, 4, 5] arr.pop() // remote last element console.log(arr) // expected output: [0, 1, 2, 3, 4] arr.shift() //remote first element console.log(arr) // expected output: [1, 2, 3, 4] arr.push('a', 'b') // add element to the end of array console.log(arr) // expected output: [1, 2, 3, 4, 'a', 'b'] arr.unshift(['red', 'yellow'], 'green') // add element to the beginning of array console.log(arr) // expected output: [['red', 'yellow'], 'green', 1, 2, 3, 4, 'a', 'b']

中間 - 插入/刪除(splice)

arr.splice(start, deleteCount, item1, item2, itemN)

const months = ['Jan', 'Feb', 'March', 'April', 'May']; months.splice(2, 1, 'yellow', 5); // remove 1 element and add elements at index 2 console.log(months); // expected output: Array ['Jan', 'Feb', 'yellow', 5, 'April', 'May']

擷取某一片段不改變原Array(slice)

arr.slice(start, end)
#包頭不包尾

const months = ['Jan', 'Feb', 'March', 'April', 'May']; months.slice(1, 3); // copy a potion from index 1 to (3 - 1) console.log(months); // 完全不影響原來的array // expected output: ['Jan', 'Feb', 'March', 'April', 'May'] console.log(months.slice(1, 3)); // expected output: ['Feb', 'March]

從尾巴添加新Array元素不改變原Array(concat)

arr.concat((value1[, value2[, [, valueN]]]))
產生新陣列:合併兩個陣列或直接添加元素到原陣列,槽狀陣列合併後可保留槽狀結構
!須注意 [ ]

const num1 = [1, 'a']; const num2 = [2, [3]]; const numsA = num1.concat(num2); const numsB = num1.concat(2, [3]); const numsC = num1.concat([2, [3]]) console.log(numsA); // expected output: [1, 'a', 2, [3]] console.log(numsB); // expected output: [1, 'a', 2, 3] console.log(numsC); // expected output: [1, 'a', 2, [3]] num2[1].push(4); // add 4 to the end of index 1 of num2 console.log(numsA); // expected output: [1, 'a', 2, [3, 4]] numsB.push(4); // add 4 to the end of numsB console.log(numsB); // expected output: [1, 'a', 2, 3, 4] numsC[3].push(4); // add 4 to the end of index 3 of numsC console.log(numsC); // expected output: [1, 'a', 2, [3, 4]]

Key-value 結構:物件 Object

Key-Value pair

儲存不同格式的資料

可儲存基本值、array、object、甚至 function

const myPhone = { name: 'myPhone', // String price: 14999, // Number features: ['long battery life', 'AI camera'], // Array hardware: { // Object ram: '8GB', storage: '64GB', } }

點記法 (dot notation) / 括號記法 (bracket notation) 賦值

括號記法(bracket notation) : ['keys']
點記法(dot notation) : .keys

myPhone['hardware'].system = 'Andriod' console.log(myPhone.hardware) // { ram: '8GB', storage: '64GB', system: 'Andriod' } console.log(myPhone['hardware']) // { ram: '8GB', storage: '64GB', system: 'Andriod' }

for-in 用法

for (key in object) { 動作(ex:console.log) }
順序檢查物件key-value pair的key,指定同時做的動作

const performance = { mike: 200, bernard: 500, cathy: undefined, jane: 300 } let sum = 0 for (let info in performance) { if (typeof(performance[info]) === 'number') { sum += performance[info] } else { console.log(`${info}` 沒交資料) } } console.log(`目前總業績:${sum}) // outpute: cathy沒交資料 // output: 目前總業績:1000

取出object資料並成為新array

取出所有的 key 值 - Object.keys()
取出所有的 value - Object.values()
取出所有的 pair - Object.entries()

const performance = { mike: 200, bernard: 500, cathy: undefined, jane: 300 } console.log(Object.keys(performance)) // ['mike', 'bernard', 'cathy', 'jane'] console.log(Object.values(performance)) // [200, 500, undefined, 300] console.log(Object.entries(performance)) // [ // ['mike', 200], // ['bernard', 500], // ['cathy', undefined], // ['jane', 300] // ]

字串

切割片段(slice、substring、substr)

str.slice(start, end) // 接受負數
str.substring(start, end) // 不接受負數
str.substr(start, length) // 接受負數

let str = "Apple, Banana, Kiwi"; console.log(str.slice(-12, 13)); // Banana console.log(str.substring(7, 13)) // Banana console.log(str.substr(-12, 6)) // Banana

斷句並建立Array(split)

str.split("以某元素斷句")
ex:
str.split(".") // 以句點斷句
str.split(" ") // 以空白斷句

let text = "Please visit Microsoft and Microsoft!"; let newText = text.split(" "); console.log(newText); // ["Please", "visit", "Microsoft", "and", "Microsoft!"]

置換字詞(replace、toUpperCase、toLowerCase)

replace:
str.replace("原字詞", "新字詞") // 置換第一個原字詞,大小寫需一致
str.replace(/原字詞/i, "新字詞") // 置換第一個原字詞,大小寫不需一致
str.replace(/原字詞/g, "新字詞") // 置換所有的原字詞

大小寫置換:
str.toUpperCase() // 全部字詞變成大寫
str.toLowerCase() // 全部字詞變成小寫

移除兩端空白(trim)

str.trim()

增加填滿字串長度(padStart、padEnd)

str.padStart(總長度, 用什麼元素填滿開頭)
str.padEnd(總長度, 用什麼元素填滿尾端)

字串轉數字/數字轉字串((+)、(*1)/toString)

數字.toString() // 數字轉字串
+(字串) // 字串轉數字方法一
(字串) * 1 // 字串轉數字方法二

從unicode找英文字符(fromCharCode)

String.fromCharCode() // 不只用來找英文字符,但用來找連續大小寫英文字符特別方便
大寫英文字符unicode從65開始
console.log(String.fromCharCode(65)) // output:A
小寫英文字符unicode從97開始
console.log(String.fromCharCode(97)) // output:a

函式function

// 把需要重複執行程式封裝進函式中
function 函式名稱(參數1, 參數2) {
執行動作
}
// 提供引數並呼叫函式,使函式依引數執行
函式名稱(引數1, 引數2)

ex: 2-1 S1A5Q1 週年慶摸彩

用箭頭函式簡化再簡化函式用法

// 省略function和程式名稱
(參數1, 參數2, …, 參數N) => { 執行動作 }

// 執行動作中如果只有一行return + 表示式,return和大括號可省略
(參數1, 參數2, …, 參數N) => 表示式;
// 等相同(參數1, 參數2, …, 參數N) => { return 表示式; }

只有一個參數時,括號可省略
單一參數 => { 陳述式; }
// 等同於 (單一參數) => { 陳述式; }

//若無參數,就一定要加括號
() => { statements }

Select a repo