RZ-Huang
    • 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
    # JavaScript 變數 ###### tags: `javascript`、`advanced` ## 資料型態 總共有 7 種資料型態,分別是 primitive type 的 6 種和 object。 #### primitive type: 1. null 2. undefined 3. string 4. number 5. boolean 6. symbol(ES6) #### object: array、function、date...等等 因此當使用`typeof`檢測一個陣列的型態時:`console.log(typeof [])`,結果會是`object`。 ### Array.isArray() 如果要知道一個資料是陣列的話,可以使用`Array.isArray()`,如果是陣列則會回傳`true`。像是下面的例子: `console.log(Array.isArray([]))` 的結果為 `true`。 ### typeof function 不過如果`typeof`檢測一個 function 的型態的話,結果會回傳`function`,而不是`object`。 ``` const val = function test(){} console.log(typeof val) ``` 像是上面 `console.log` 的結果就是`function`。 ### 廣為人知的型態 bug `console.log(typeof null)` 得出來的結果是 `object`,而不是 `null`,這是最一開始 javascript 就存在的 bug。 ### 較精確的資料型態檢測 使用`Object.prototype.toString.call()` 的方式比起使用`typeof`可以更精確顯示資料的型態,如下的範例: ``` const checkList = [1, 'Hello', [1, 2], new Date(), function (){}, true, undefined, null]; for (let i = 0; i < checkList.length; i += 1) { const checked = Object.prototype.toString.call(checkList[i]); console.log(checkList[i], checked); } ``` 結果為: ``` 1 '[object Number]' Hello [object String] [ 1, 2 ] '[object Array]' 2019-08-09T08:20:15.940Z '[object Date]' [Function] '[object Function]' true '[object Boolean]' undefined '[object Undefined]' null '[object Null]' ``` 在`[object XXX]`的那個`XXX`字串即為資料的型態。 #### 參考資料 1. [Object.prototype.toString()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) ### Primitive type 和 Object 的最大差別 Primitive type 的資料型態都是不可變的(Immutable),比如下面的例子: ``` let str = 'hello' str.toUpperCase() console.log(str) ``` 結果依然會是 `str` 本身的 `hello` 值,`toUpperCase()` 這個方法沒辦法改變`str` 原始的值,`str.toUpperCase()` 回傳的結果是一組被修正過、新的字串,並不會影響到原本的變數,得要再用一個變數去接這個結果: ``` let str = 'hello' let newStr= str.toUpperCase() console.log(newStr) ``` 這個`newStr`的結果就會是`HELLO`。 而像 array 使用 `push()` 的方法就可以改變原始的陣列值: ``` let arr = [1] arr.push(2) console.log(arr) ``` ## 「=」賦值 prmitive type 和 object 的另一個最大差別就是**賦值**的方式不同,下面來直接舉例。 Primitive type: ``` var a = 10 var b = a console.log(a, b) // 10 10 b = 5 console.log(a, b) // 10 5 ``` 第一個`console.log()`的結果 `a` 與 `b` 都是 `10`;第二個則是`a` 為`10`,`b` 為 `5`。 接著我們再看 object 的範例: ``` var obj = { number: 1 } var obj2 = obj console.log(obj, obj2) // { number: 1 } { number: 1 } obj2.number = 5 console.log(obj, obj2) { number: 5 } { number: 5 } ``` 看結果會發現到只改了 `obj2` 的 `number` 值,但卻連 `obj` 的 `number` 的值也跟著一起改變了。 原因在於 primitive type 和 object 的賦值方式不同。第一個 primitive type 的範例其實可以看成這樣的演變過程: ``` a: 10 // var a = 10 b: 10 // var b = a b: 5 // b = 5 ``` 因此最後 `a` 的結果是 `10`,`b` 的結果是 `5`,因為 `b = a` 這個意思其實只是拷貝了 `a` 所擁有的值(10)而已,而不是拷貝整個 `a` 這個變數當作 `b`。 而 object 的範例可以看成這樣: 第一個步驟`var obj = {number: 1}` 把它看作兩個動作,第一個動作是給予`{number: 1}`這個值一個記憶體空間,接著 `obj` 才去存取`{number: 1}`這個值的記憶體位置。 ``` 0x01: { number: 1 } obj: 0x01 ``` 第二個步驟`var obj2 = obj`則是去存取 `obj` 的值,`obj` 儲存的值為 `0x01` 的記憶體位置 ``` obj2: 0x01 ``` 第三個步驟`obj2.number = 5`所更改的值實際上是去更改`0x01`這個記憶體位置當中`number` 的值 ``` 0x01: { number: 5 } ``` 因為實際上`obj`與`obj2`兩個值所指到的記憶體位置是相同的,而記憶體位置裡的值被更改理所當然兩個值會同步被更新。換句話說,今天第三步驟變成`obj.number = 5` 其實結果也會是一樣的。 總結來說,primitive type 與 object 的賦值差別在於,object 賦值的方式是一個物件的記憶體位置,而 primitive type 則是利用拷貝的方式給予一個值。 不過如果是這樣的 object 範例: ``` var obj = { number: 1 } var obj2 = obj console.log(obj, obj2) // { number: 1 } { number: 1 } obj2 = { number: 5 } console.log(obj, obj2) // { number: 1 } { number: 5 } ``` 變成`obj2 = {number: 5}`這裡已經重新把`obj2`的值導到`{number: 5}`的記憶體位置了,所以不會影響到`obj`的結果。 ## 「==」和「===」的差別 `==` 與 `===` 兩個都可以拿來當作比較變數間是否相等,但是實務上強烈建議只使用`===`來當作比較的符號,因為如果使用`==`的話,會有資料型態轉換的瑕疵,比如說:`console.log(1 == '1')` 實際上會是 `true`,因此沒事不要使用`==`。 如果對於兩個長得一樣的 object 做比較的結果會是`false`,因為兩個物件實際上是使用記憶體位置來做比較,因此就算值一樣,但怎麼比都不會一樣,如下範例: ``` console.log([] === []) // false var obj = [1] var obj2 = [1] console.log(obj === obj2) // false var obj = {number: 1} var obj2 = {number: 1} console.log(obj === obj2) // false ``` 另外 `console.log(NaN === NaN)` 這個結果會是 `false`,因為`NaN` 不屬於任何的值。

    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