chunwen
    • 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
    • Make a copy
    • 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 Make a copy 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
    # [筆記]JavaScript:物件(Object)、陣列(Array)介紹 下面內容引用自[重新認識 JavaScript: Day 04 物件、陣列以及型別判斷](https://ithelp.ithome.com.tw/articles/10190962)、六角學院、[PJCHENDer部落格](https://pjchender.blogspot.com/2016/01/javascriptobject.html)、[你懂 JavaScript 嗎?#17 物件(Object)](https://cythilya.github.io/2018/10/24/object/)、[MDN-JavaScript 物件基礎概念](https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Objects/Basics) ## 何謂物件(Object)? ### 所有基本型別 (Primitives) 以外的值都是物件。 我們可以從 [ECMA 262](https://www.ecma-international.org/ecma-262/6.0/) 標準來看物件的定義 > 「An object is a collection of properties and has a single prototype object.」 翻成白話文就是,物件是一個從零至多種屬性的集合,而**屬性是鍵 (key) 與值 (value) 之間的關聯**。 一個屬性的「值」可以是某個基本型別(string、number、boolean等),也可以是另一個物件,甚至可以是一個函數。 物件可以是瀏覽器預先定義好的,當然也可以是由自己定義物件的屬性與內容。 > 覺得太複雜嗎?沒關係,那請先記得物件(Object)就是很多「名稱與值」(key-value)的配對。重點在於值可以放入哪些種類? 1. 原生的值(primitive),像是布林值(Boolean)、數值(Number)或是字串(String),而在物件當中,我們把這類的值稱做屬性(Property)。 2. 物件(Object),也就是在一個物件裡面再嵌入一個物件,這種以物件為值的情況我們也把它稱作屬性(Property)。 3. 函數(function),在物件的情況下,我們會把這種函式稱做方法(method)。 >補充:這三種類型的值在口語上又被分為屬性和方法(這邊說的屬性和物件的屬性無關!)[屬性(property)與值(value)名詞確認](https://www.udemy.com/javascript-learning/learn/lecture/6789162#questions/7628838) ## 物件及屬性 早期,要建立一個自定義的物件可能會透過 new 關鍵字來建立一個物件實體,再替這個物件新增屬性與方法: ```javascript= var person = new Object(); person.name = 'Andy'; person.job = 'Front-end developer'; person.sayName = function() { alert( this.name ); }; ``` 後來,另一種建立物件的方式更為簡便,也是目前最常見的: ```javascript= var person={ name: 'ANDY', job: 'Front-end developer', sayName: function() { alert( this.name ); } } ``` 1. > 這種建立物件的方式稱為「**物件實字** (Object literal)」,同時也是 `JSON` 格式的核心語法。 2. > 用大括號將要新增屬性方法直接放入 ## 屬性存取方式介紹 ### dot notation `.` 點陣法 用法如下 ```javascript= var farm={ farmer:['Andy','Jacky','Allen'], fruit:['banana','apple'], location:'taipei' } console.log(farm.farmer[0]) //Andy 我們可以透過·.·來進行存取 ``` > 注意:dot notation不能存取以數字開頭屬性或其他([不合法的 JavaScript 的識別字](http://www.ablmcc.edu.hk/~scy/home/javascript/identifier.htm)),但可以存取關鍵字、保留字、$或底線 ### bracket notation `[]` 括弧記法 用法如下 ```javascript= var farm={ farmer:['Andy','Jacky','Allen'], fruit:['banana','apple'], location:'taipei' } console.log(farm['farmer'][0]) //Andy 我們可以透過·[]·來進行存取 ``` >[ ] 裡面如果放的是字串而不是變數,要記得加上引號’‘ ## 屬性新增/刪除/判斷是否存在 ### 屬性新增 直接用=即可,用法如下 ```javascript= var object={} object.name='Andy' object.name; //Andy ``` ### 屬性刪除 ```javascript= var object={} object.name='Andy' delete object.name; object.name; //undefined ``` ### 判斷屬性是否存在 使用 in 或 hasOwnProperty() ```javascript= var obj = { name: 'Object' }; // 透過 in 檢查屬性 console.log( 'name' in obj ); // true console.log( 'value' in obj ); // false // 透過 hasOwnProperty() 方法檢查 obj.hasOwnProperty('name'); // true obj.hasOwnProperty('value'); // false ``` ## 陣列介紹 陣列簡單來說就是存取一系列的值,且值與值之間是有相關聯的 EX:農場裡的玉米田A、玉米田B 更詳細說法我們引用自Kuro大大文章 如下 > JavaScript 的陣列可以看作是一種特別的「物件」,同樣是零至多個元素的集合,且並沒有規定它能放什麼東西進去。 陣列內可以是原始的資料類型、其他陣列、函式、物件等等。 要注意的是,陣列是個有順序性的集合,且只能透過 `[] `來存取。 建立陣列同樣也可以透過 new 關鍵字來建立 ```javascript= var a = new Array(); a[0] = "apple"; a[1] = "boy"; a[2] = "cat"; a.length; // 3 ``` 實務上,還是比較常用陣列實字 (Array literal) ```javascript= var a = []; a[0] = "apple"; a[1] = "boy"; a[2] = "cat"; a.length; // 3 或是 var a=['apple','boy','cat'] a.length; // 3 ``` 陣列的長度可以由 `ARRAY.length` 來取得,而且 `length` 這個屬性的值是可以被覆寫的。範例如下 ```javascript= var a=['apple','boy','cat'] a.length; //3 故意將長度更改為1 a.length=1; console.log(a); //["apple"] a.length=3; console.log(a); // ["apple", undefined, undefined] ``` > 上面的例子中,陣列 a 原本的長度為 3,後來透過 a.length = 1; 設定成 1 之後,後面的元素就被移除了。即使之後再度修改成 a.length = 3;,後面的兩個元素也只會被 undefined 所填補。 所以,我們發現陣列長度可以隨時增加或減少, ```javascript= var array = ['a', 'b', 'c']; array.length; // 3 array[7] = 'z'; console.log(array); // ["a", "b", "c", undefined, undefined, undefined, undefined, "z"] ``` 最後,來介紹一下如何新增陣列中的值 `ARRAY.push()` ```javascript= var array = ['a', 'b', 'c']; array.push('d'); console.log(array); //['a', 'b', 'c','d'] ``` 其他的增減方法,如 `ARRAY.pop()`、 `ARRAY.shift()` 、 `ARRAY.unshift()` 可以到 [MDN Array](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array)了解 ###### tags: `object` `array`

    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