Naomi AC學習筆記
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Javascript 筆記 > Updated date:Alpha Camp 2-1 S3 [TOC] ## 迴圈系列 ### whlie迴圈(while、do while) :::info **while(條件式) {執行動作}** // 若符合條件則執行,每次執行前檢查條件 **do {執行動作} while(條件式)** // 先執行再檢查條件,若符合則再執行一次直到不符合為止 應用:[2-1 S1A5Q1週年慶摸彩](https://replit.com/@WuwachonWu/2-1-S1A5Q1-Zhou-Nian-Qing-Mo-Cai-Wan-Zheng-2#index.js/) 彩卷號碼產生並檢查有無重複 ::: ```javascript= 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) :::info **for (let i = 0; i < n; i++) {執行動作}** // 太常用不解釋 **for (let key in object) {執行動作}** // 依***物件***的key逐項執行,陣列和字串也可用 **for (let value of array) {執行動作}** // 依***陣列***的值逐項執行,物件和字串不能用 ::: ```javascript= 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) :::info **陣列.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) => {條件}) ::: ```javascript= 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) ![](https://i.imgur.com/miNE3QE.png) :::info * **arr.shift()** * **arr.unshift(element1[, ...[, elementN]])** * **arr.pop()** * **arr.push(element1[, ...[, elementN]])** ::: ```javascript= 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) :::info **arr.splice(start, deleteCount, item1, item2, itemN)** ::: ```javascript= 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) :::info **arr.slice(start, end)** #包頭不包尾 ::: ```javascript= 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) :::info **arr.concat((value1[, value2[, ...[, valueN]]]))** 產生新陣列:合併兩個陣列或直接添加元素到原陣列,槽狀陣列合併後可保留槽狀結構 !須注意 [ ] ::: ```javascript= 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** ![](https://i.imgur.com/h15Tjb0.png) ### 儲存不同格式的資料 :::info 可儲存基本值、array、object、甚至 function ```javascript= 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)** 賦值 :::info 括號記法(bracket notation) : ['keys'] 點記法(dot notation) : .keys ::: ```javascript= 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 用法 :::info **for (key in object) { 動作(ex:console.log) }** 順序檢查物件key-value pair的key,指定同時做的動作 ::: ```javascript= 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 :::info 取出所有的 key 值 - Object.keys() 取出所有的 value - Object.values() 取出所有的 pair - Object.entries() ::: ```javascript= 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) :::info str.slice(start, end) // 接受負數 str.substring(start, end) // 不接受負數 str.substr(start, length) // 接受負數 ::: ```javascript= 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) :::info **str.split("以某元素斷句")** ex: str.split(".") // 以句點斷句 str.split(" ") // 以空白斷句 ::: ```javascript= let text = "Please visit Microsoft and Microsoft!"; let newText = text.split(" "); console.log(newText); // ["Please", "visit", "Microsoft", "and", "Microsoft!"] ``` ### 置換字詞(replace、toUpperCase、toLowerCase) :::info **replace:** str.replace("原字詞", "新字詞") // 置換**第一個**原字詞,大小寫需一致 str.replace(/原字詞/i, "新字詞") // 置換**第一個**原字詞,大小寫不需一致 str.replace(/原字詞/g, "新字詞") // 置換**所有的**原字詞 **大小寫置換:** str.toUpperCase() // 全部字詞變成大寫 str.toLowerCase() // 全部字詞變成小寫 ::: ### 移除兩端空白(trim) :::info str.trim() ::: ### 增加填滿字串長度(padStart、padEnd) :::info str.padStart(總長度, 用什麼元素填滿開頭) str.padEnd(總長度, 用什麼元素填滿尾端) ::: ### 字串轉數字/數字轉字串((+)、(*1)/toString) :::info 數字.toString() // 數字轉字串 +(字串) // 字串轉數字方法一 (字串) * 1 // 字串轉數字方法二 ::: ### 從unicode找英文字符(fromCharCode) :::info **String.fromCharCode()** // 不只用來找英文字符,但用來找連續大小寫英文字符特別方便 **大寫英文字符unicode從65開始** console.log(String.fromCharCode(65)) // output:A **小寫英文字符unicode從97開始** console.log(String.fromCharCode(97)) // output:a ::: ## 函式function :::info **// 把需要重複執行程式封裝進函式中** function 函式名稱(參數1, 參數2) { 執行動作 } **// 提供引數並呼叫函式,使函式依引數執行 函式名稱(引數1, 引數2)** ex: [2-1 S1A5Q1 週年慶摸彩](https://replit.com/@WuwachonWu/2-1-S1A5Q1-Zhou-Nian-Qing-Mo-Cai-Wan-Zheng-2#index.js/) ::: ### 用箭頭函式簡化再簡化函式用法 :::info **// 省略function和程式名稱** (參數1, 參數2, …, 參數N) => { 執行動作 } **// 執行動作中如果只有一行return + 表示式,return和大括號可省略** (參數1, 參數2, …, 參數N) => 表示式; // 等相同(參數1, 參數2, …, 參數N) => { return 表示式; } **只有一個參數時,括號可省略** 單一參數 => { 陳述式; } // 等同於 (單一參數) => { 陳述式; } **//若無參數,就一定要加括號** () => { statements } :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully