Peiyun Lee
    • 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
    ###### tags: `前端技能樹` # 初探Javascript基本功能 — 函式、迴圈 / 陣列、物件 在前一篇,我們提到了一些 Javascript 的語法和基本功能,包括宣告變數、資料型別、條件陳述式,接下來就繼續來了解迴圈、函式、物件、陣列的觀念和用法。 ## 流程控制 — 迴圈 有時候希望可以**自動重複執行某些動作**,JavaScript 提供了各式各樣的迴圈機制,讓我們能夠用不同的方法來執行重複動作,比如 ```for```、```while```、```do...while``` ...等。 以 ```for``` 來說明,一個 ```for``` 陳述式通常會長成下面這個樣子: ```javascript= for (let i = 0; i < 10; i++){ //執行任務 } ``` 分別講解一下 ```for``` 的結構和作用流程,當迴圈開始執行的時候: - **Step1:執行初始表達式 ```let i = 0```**,這個變數 ```i``` 通常會作為迴圈計數器,用來控制迴圈的重複執行。 - **Step2:判斷條件式 ```i < 10```**,如果結果為 true,則會繼續第三步驟執行任務;如果結果為 false,迴圈就會終止。 - **Step3:執行區塊內指定的重複動作** - **Step4:更新迴圈計數器 ```i++```**,讓變數 ```i``` 加一以便執行下一次的動作,接下來迴圈就會重複第二步驟~第四步驟,直到判斷條件式的結果為 false 才終止迴圈。 舉例來說,要自動將數值 ```k``` 從零開始,每次加二重複十次: ```javascript= let k=0; for (let i = 0; i < 10; i++){ k = k + 2; } console.log(k) //20 ``` ## 函式(Function) **函式(Function)是用於執行某個任務的程式碼區塊**,可以選擇性的定義傳入的參數(數據),讓程式碼模組化易於維護和修改。舉例來說,一個基本的函式會長成這樣: ```javascript= function test(num) { let result = num * 20; return result; } ``` - **函式名稱 - ```test```** - **參數 - ```num```** - **函式執行的任務 - ```{...}```**:可用 ```return``` 在函式執行後回傳數值 ### 箭頭函式(Arrow Function) 除了透過關鍵字 ```function``` 定義函式,**還有另一種建立函式的方法 — 箭頭函式(Arrow Function)**: ```javascript= let test = (num) => { let result = num * 20; return num * 20; } ``` ### 呼叫函式執行 定義出函式的參數和執行的任務後,就可以透過呼叫函式```函式名稱()```來執行任務,如果有回傳值會儲存到所指定的變數中。 ```javascript let answer = test(5); //100 ``` ## 物件(Object) 在Javascript裡,**物件(Object) 擁有與自身相關的資料,包含屬性(properties) 或函式(methods)**,可以看做是資料模型,方便我們去建立、存取物件的數據。 ### 宣告物件 物件的內容會由大括號 ```{}``` 包住;屬性可以當作是用在物件內部的變數,只是在宣告物件時要用冒號 ```:``` 賦予其值。舉例來說,一個物件可能會長成這樣: ```javascript= let obj = { name: "May", score: 80, introduction: function () { console.log("I'm a student") } }; ``` ### 取得物件屬性 取得物件屬性的方法,可以在物件名稱後使用點符號 ```.``` 或是 ```['屬性名稱']``` 來存取;函式的話記得要加上小括號 ```()``` 來呼叫;而要修改物件屬性的值就會跟一般變數的用法一樣,用等於 ```=``` 修改值: ```javascript= obj.property_1 = "Bob"; obj.name //'Bob' obj['score'] //80 obj.introduction() //"I'm a student" ``` ## 陣列(Array) **陣列(Array)是一種似列表(list-like)的物件**,可以將資料儲存形成一連串的數組,沒有固定的長度或是型別限制。 ```javascript let fruits = ["apple", "banana", "orange"]; ``` ### 取得陣列元素 取得陣列中某個數值的方法,可以在陣列名稱後使用 ```[索引值]``` 來存取,而所有陣列的元素索引值都是從 0 開始;若是要修改陣列元素的值也是用等於 ```=``` 來修改: ```javascript= fruits[0] = 'watermelon' fruits[0] //"watermelon" fruits[1] //"banana" fruits[2] //"orange" ``` ### 陣列方法 因為陣列是一種物件,**本身原型(Prototype)擁有各種預設的方法(Methods),可以用來針對陣列執行一些操作**,比如新增刪除元素的 ```push``` / ```pop```、遍歷陣列內每個元素的 ```forEach``` / ```map```...等等。 - **```push```**:加入新的項目至陣列末端 ```javascript= fruits.push('peach') //["watermelon", "banana", "orange", "peach"] ``` - **```pop```**:移除陣列末端項目 ```javascript= fruits.pop() //["watermelon", "banana", "orange"] ``` - **```forEach```**:遍歷陣陣列內的每個元素,傳入指定的函式並執行。 ```javascript= fruits.forEach(function(item, index) { console.log(item, index); }); //"watermelon" 0 //"banana" 1 //"orange" 2 ``` - **```map```**:遍歷陣陣列內的每個元素,依據經由函式運算後所回傳的結果,建立一個新的陣列。 ```javascript= const newArray = fruits.map((item,index) => item + index ); console.log(newArray); // ["watermelon0","banana1","orange2"] ``` ## 小結 跟上一篇一樣直接利用一個小範例來當作結尾,複習今天提到的一些觀念。現在想要計算幾個學生的平均成績,我們將所有資料儲存在一個物件中,分別有每個學生的姓名、三項成績: ```javascript= let data = [ { name: "May", score: [90, 80, 40]}, { name: "Bob", score: [77, 88, 66]}, ]; ``` 接著定義函式,要根據傳入的學生資料,將所有成績加總,計算出平均成績儲存到物件當中: ```javascript= function Average(student) { let total = 0; student.score.forEach((item) => { total += item; }); student.average = total / student.score.length; } ``` 最後使用 Array.forEach ,呼叫函式計算每個學生的平均成績,並且印出結果,這樣就完成了今天的內容囉! ```javascript= data.forEach((item) => { Average(item); console.log(`${item.name}的平均成績是${item.average}`); }); // "May的平均成績是70" // "Bob的平均成績是77" ``` 👉 如果文章中有錯誤的地方,要麻煩各位大大不吝賜教;喜歡的話,也要記得幫我按讚訂閱喔❤️ ### 參考資料 - [MDN - Javascript](https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript)

    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