wywsmail
    • 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 New
    • 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 Note Insights Versions and GitHub Sync 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: 投稿文章 --- ![image](https://i.imgur.com/w8IpW7q.jpg) # JavaScript 的陣列 (Array) 與物件 (Object) 之前曾經介紹過宣告變數,開頭用 `var` 後接數字 (Number) 或是字串 (String),而今天我們要介紹另一種變數型態,就是陣列 (Array) 與物件 (Object),其實陣列也算是物件的一種,因為我們在 console 輸入 `tyoeof(變數)` 所顯示的都是 `object`,我們可以先簡單的想像陣列與物件就是將變數的值宣告為一串的綜合資料就是了,其中的差異我們後面再解釋清楚。 ## 何謂陣列 用中括號 `[]` 包覆起來的資料,就是陣列,而陣列可以一次記錄好幾個資料,每一個中間用 `,` 分開即可。 ### 陣列的寫法 * 所以下方5個變數哪一個變數後面是陣列呢? ```js var Farmer = 'Alec Wang'; var appleField = [8, 5, 6]; var cats = ['小蜜', '波比']; var birds = 3; var rabbits = 5; ``` * 很簡單,答案揭曉,就是有中括號的就是陣列 ```js var appleField = [8, 5, 6]; var cats = ['小蜜', '波比']; ``` ### 陣列的讀取 * 陣列的世界是從 `0` 開始的,而不是從 `1` 開始,所以如果我們要取出某陣列的值的話,我們必須要像下面這樣的寫法。 ```js var appleField = [8, 5, 6]; var cats = ['小蜜', '波比']; console.log(appleField[0]); // console 顯示為 8 console.log(cats[1]); // console 顯示為"波比" ``` ### 陣列的增加或更改內容 * `.push` 可以從後方增加值 ```js var appleField = [8, 5, 6]; var cats = ['小蜜', '波比']; appleField.push(10); cats.push('小胖'); console.log(appleField); // console 顯示 [8, 5, 6, 10] console.log(cats); // console 顯示 ["小蜜", "波比", "小胖"] ``` * 或是用指定位置的方式直接變更 & 新增內容 ```js appleField[2]=50; cats[3]="娜娜"; console.log(appleField); // console 顯示 [8, 5, 50, 10] // 直接替換掉了原本 [2] 位置的 6 console.log(cats); // console 顯示 ["小蜜", "波比", "小胖", "娜娜"] // 直接於後續位置 [3] 新增資料 "娜娜" ``` ### 陣列的長度 * 利用 `.length` 的方式可以知道此陣列有多少筆資料,這個在之後介紹迴圈的時候就會頻繁的遇到,我們用 `console.log` 來讓它顯示比數然後再用字串疊加的方式顯示一段文字吧。 ```js console.log(cats.length); // console 顯示 4 console.log('我總共有' + cats.length + '隻貓,分別是' + cats[0] + '、' + cats[1]+ '、' + cats[2] + '及' + cats[3]); // console 顯示 "我總共有4隻貓,分別是小蜜、波比、娜娜及小胖" ``` ## 何謂物件 用大括號 `{}` 包覆起來的資料,就是物件,而物件可以一次記錄好幾個不同類別的資料,而類別與後面的值,中間用 `:` 連結,每一個類別中間用 `,` 分開即可,物件就像是將一堆有關係的資料們全部群組在一起,所組成的集合資料。 ### 物件的寫法 * 將原本的陣列資料改寫成物件,如下 ```js var farm = { farmer: 'Alec Wang', appleField: [8, 5, 6], cats: ['小蜜', '波比'], birds: 3, rabbits: 5 } ``` * 原本的陣列方式,雖然已可以同時記錄好幾組資料,但還是仍必須要宣告好幾個變數,才能夠將那些資料逐一地記錄起來,但現在用物件的方式只要宣告一個變數即可,資料可以用類別的方式在 `{}` 內被記錄起來。 ### 讀取物件內容 * 要將物件內的資料取出使用,首先要先寫 '變數名稱' 然後後接一個 '.' 再接上類別名稱,後面再用 `[]` 內填上資料位置,像是這樣 `farm.cats[1]`,然後記得 `[0]` 才是第一個。 ```js console.log(farm.cats[1]); // console 顯示為 "波比" console.log(farm.farmer + '的農場裡有' + farm.cats.length + '隻貓,最喜歡的是' + farm.cats[1]); // console 顯示為 "Alec Wang的農場裡有2隻貓,最喜歡的是波比" ``` ### 新增物件內容 至於要怎麼樣在物件中新增內容呢?我們可以宣告一個空的物件像下面這樣,就是 `{}` 裡面都先空空的,再一個一個的把資料新增進去。而新增資料的方式就是 `變數名稱` 後面接 `.` 再接要新增的 `類別名稱` 再接一個 `=` 然後就是它的值,陣列也可以。 ```js var store = {}; store.pigs = 15; store.boss = ['Bruce', 'Eason']; console.log('這間店的老闆有 ' + store.boss.length + ' 位,一位是 ' + store.boss[0] + '另一位是 ' + store.boss[1] + '目前總共養了 ' + store.pigs + ' 隻小豬'); // console 顯示 "這間店的老闆有 2 位,一位是Bruce另一位是Eason目前總共養了15隻小豬" ``` ### 物件 + function * 物件除了可以記錄資料之外,還可以與 `function` 結合在一起,讓這一整組物件變成一個完整的系統,寫法像是下面這樣,其中一個 `people` 類別直接接上了 `function`,這個 `function` 不需要命名,最後再用執行 `function` 的方式執行。 ```js var market = { boss: 'Rita', staffs: ['Alec', 'Arron'], section: ['meat', 'vegi'], meat: [15, 20, 25, 30], vegi: [3, 6, 9, 12], people: function(){ console.log('這間市場的老闆是 ' + market.boss + ',員工是 ' + market.staffs[0] + ' 與 ' + market.staffs[1]); } }; market.people(); ``` ### 設計流程 (物件 + 陣列) 如果要將好幾個物件全部都記錄在一起呢?那就再把這些物件組成陣列,就像下面這個樣子。 ```js var house = [{ person: 'Alec', cats: ['小蜜', '波比'] },{ person: 'Eason', dogs: ['吉利', '寶寶'] }]; console.log(house[0].person + '家有' + house[0].cats.length+ '隻貓,' + house[0].cats[0] + '和' + house[0].cats[1]); // console顯示 "Alec家有2隻貓,小蜜和波比" console.log(house[1].person + '家有' + house[1].dogs.length+ '隻狗,' + house[1].dogs[0] + '和' + house[1].dogs[1]); // console顯示 "Eason家有2隻狗,吉利和寶寶" ``` `var house` 是一個陣列,而這個陣列裡面的值是由兩個物件所組成,而這兩個物件裡面各自的值則由一個字串與一個陣列組成,當要把資料調出來的時候,記得只要用讀取陣列與物件的方式把資料調出來就可以囉。 陣列與物件就是這麼有趣,可以幫我們記憶很多大量的資料,可以合併使用,也可以單獨使用,今天就介紹到這裡囉,謝謝大家。 ## 參考資料 * 六角學院課程: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