grayshine
    • 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
    # <font class="h2">強制轉型coercion</font> ###### tags: `javascript` <style> .h2 { background: linear-gradient(135deg,#fff,#537479) ; color: #537479; display:block; padding: 6px 5px; border-radius: 4px; } .h3 { background: linear-gradient(180deg,#fff 50%,#c9d5d4) ; color: #537479; display:block; padding: 6px 5px; border-bottom: 3px solid #537479; } .h4 { color: #537479; font-weight:bold; font-size:1.1em; } </style> <br> 只要是布林的那邊會自動使用toNumber()自動轉型 字串也會使用toNumber()自動轉型 ```javascript 2 == true //false true == 'false' //false true == '0' //false ``` <br><br><br> javascript是「動態型別」的語言,javaScript想要兩個不同型別的數值做運算時,必須把這兩個數值轉換為同一種類型,這時有兩方式轉型「明確的」強制轉型explicit coercion、「隱含的」強制轉型implicit coercion <br> 強制轉型只有三種類型 - 轉為字串 - 轉為布林 - 轉為數字 <br> | | 明確的(手動)| 隱含的(自動) | 物件的強轉 | | ------------ | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | --- | | **轉為字串** | `toString()`、`String()` | `+`運算子 | `toString` | | **轉為布林** | `Boolean()` | ➤邏輯運算子`&&`、ll、`! `<br>➤`if`或`while`等陳述式條件區塊 |都會被轉為`ture`| | **轉為數字** | `parseInt()`、`parseFloat()` `Number()` | ➤大小於運算子(`>`、`<`、`<=`、`>=`)<br>➤ 算數運算子(`-`、`+`、`*`、`/`、`%`<br>使用`+`號的時候當中不能有字串)<br>➤寬鬆的數值比較(`==`、`!=`) | `valueOf` | <br> ### <font class="h3">「明確的」強制轉型explicit coercion</font> ### <font class="h4">➤轉為數字</font> `parseInt()`、`parseFloat()` 與 `Number()` 例: ```javascript let age ="30"; //"30" 為字串 let age =parseInt("30"); //此時"30"被轉為數字型別 ``` :::info :bulb: 表單取出的數字會是字串string,需要把它轉為數字,會常用到 ::: :::info 如果無法轉成數字,則會回傳`NaN` ```javascript Number(true)//1 Number(null)//0 Number(false)//0 Number("\n")//0 Number("12s")//NaN Numbet(undefined)//NaN ``` :bulb:比較特別的部分是`ture`會轉成數值1;`false`會轉成數值0`null`會被轉為0,`undefined`會被轉成`NaN` :bulb:數字+`undefined`會是`NaN` <br> :::danger | 值 | ture | false | null | undefined | NaN | | -------- | ---- | ----- | ---- | --------- | --- | | 傳換數字 | 1 | 0 | 0 | NaN | NaN | ::: :::danger ### 判斷變數是否為NaN: ```javascript NaN == NaN //false,NaN無法判斷出來,所以必須使用isNaN Number.isNaN(變數) //ECMAScript正規寫法 isNaN(變數) //非正式寫法 ``` ::: :arrow_right:[parseInt、parseFloat 與 Number 轉換成數字的三種方法](https://medium.com/unalai/%E8%AA%8D%E8%AD%98-parseint-parsefloat-%E8%88%87-number-%E8%BD%89%E6%8F%9B%E6%88%90%E6%95%B8%E5%AD%97%E7%9A%84%E4%B8%89%E7%A8%AE%E6%96%B9%E6%B3%95-276640aedb4e) <br><br><br><br><br><br> ### <font class="h4">➤轉為字串 </font> `toString()`、`String()` ### 語法 ```javascript (N).toString(進制位) ``` 例: ```javascript let b =1; b = b.toString(10); //'1' (123).toString(); //'123' 123..toString(); //奇特寫法可以作用 '123' ``` ### 可以拿來轉進位數 ```javascript (10).toString(2) //''1010'' ``` :::info **String()與 .toString()的區別** `toString()`可以將所有的的資料都轉換為字串,但是要排除`null` 和 `undefined` `String()`可以將null和undefined轉換為字串,但是沒法轉「進位制字串」 ::: <br><br><br><br><br><br> ### <font class="h4">➤轉為布林</font> 使用`Boolean()` 「假值Falsy Value」(`null`, `0`, `NaN`, 空字串 (`""`),或 未定義`undefined`)一定會被轉為false。 除了「假值Falsy Value」以外的「真值 Trusy Value」會被轉為true :::info 例: ```javascript Boolean("some string")//true Boolean({}) //true Boolean(function(){})//true Boolean([]) //true ``` ::: :arrow_right:[JS 真值表](https://thomas-yang.me/projects/oh-my-dear-js/) <br> ### <font class="h3">「隱含的」強制轉型implicit coercion</font> **自動轉型**,隱性轉換則來自於JS在運算過程中的規則 <br> ### <font class="h4">➤轉為字串</font> 當使用到`+`運算子時觸發 加號兩側其中一方是字串,則將兩側都視為字串。(不是字串的將自動轉型成字串) :::info ```javascript let myName = 'Tom'; let age = 18; let total = myName + age; console.log(typeof total);//string //age原本是number,相加後變成字串 console.log("hi 我是"+myName+,"我今年18歲")//hi 我是Tom,我今年18歲 ``` age原本是number,相加後變成字串 ::: :::spoiler 周末記憶體接龍: ```javascript let a = 1; let b = a++; let c = a + b; let d = '3'; c = c + d; console.log(c); ``` `let b = a++;`:先執行完該行程式碼後,在執行運算式。 `c = c + d; //'33' `:加號兩側其中一方是字串,則將兩側都視為字串。(不是字串的將自動轉型成字串) ![](https://i.imgur.com/mtn5MQe.png) ```javascript let a = "b" let b = "a" let c = "a" let d = a + b + + c + c ;//+c無法解析因此回傳 NaN console.log(d)//b' + 'a' + 'NaN' + 'a' = 'baNaNa' ``` ::: <br> ### <font class="h4">➤轉為布林</font> - **邏輯運算子`&&`、`||`、`!`** - **`if`或`while`等陳述式條件區塊** :::info 範例: ```javascript console.log(!0);//true //因為0會轉換為false,!為反轉的意思 console.log(`1` == !0);//ture //布林跟字串比對時都會轉成數字 ``` ::: :::info 短路解析 邏輯運算式是由左向右解析的, 他們會以下列規則嘗試進行 短路解析: `false` && 任何東西 是 false 的短路解析。 `true `|| 任何東西 是 true 的短路解析。 ```javascript var a2 = true && false; // false var a3 = false && true; // false var a6 = false && "Cat"; // false var a7 = "Cat" && false; // false ``` ```javascript var o2 = false || true; // true var o3 = true || false; // true ``` ::: <br> ### <font class="h4">➤轉為數值</font> - 大小於運算子(`>`、`<`、`<=`、`>=`) - 算數運算子(`-`、`+`、`*`、`/`、`%`) :::danger 使用`+`號的時候,只要其中有一個值是String字串,那麼就不會觸發數字轉型,而是轉字串 ::: - 在任一類型的數值前面使用加法運算子`+`來觸發轉型 - 寬鬆的數值比較(`==`、`!=`) :arrow_right:[真值表](https://dorey.github.io/JavaScript-Equality-Table/) :::info 字串範例: ```javascript let g = 8; let h = "8"; console.log(g*h==88);//64,false console.log(g*h==64);//64,true console.log(g*h===64);//64,true //因為類別已經被轉為數字了 let i = "9"; let j = "9"; console.log(i+j==99);//true console.log(i+j=="99");//true console.log(i+j===99);//false ``` ::: :::info 布林加減乘除特別例子: ```javascript let a = true + true ; //2,number let b = false + 123 ;//123,number let e = true > false ;//true,boolean let f = true == 1 ;//true,boolean console.log(true == '1')//true,boolean ``` ::: :::info null範例 ```javascript let c = null + 123 ; //123,number let d = null + '123'; //`null123`,string //加號遇到字串,會全部轉為字串 ``` ::: :::danger null的特別例子 null跟undefined,不會使用number()來強轉型 ```javascript console.log(null == 0);//false console.log(null == undefined);//ture ``` ::: :::danger ==`NaN` 運算,結果都會是`NaN`== ::: <br><br><br><br> ### <font class="h3">便利方法</font> :::info ### ➤轉為字串: 在想要轉型的數值後面與空字串相加 ```javascript 5+"" ``` <br> ### ➤轉為數值: ==利用一元運算子會轉正負號(二元運算子會變字串)== ```javascript +"5" //5,與Number(5)效果是相同的 ``` ```javascript -"5" //-5 ``` ```javascript "5"-0 //5 ``` ### 其他轉為數字方法 `>>0`等於`Math.floor()`,也是取整的寫法,也可以寫`|0`, 或是`~~` ```javascript 3.14>>0 //3 3.14|0 //3 ~~3.14 //3 '3'>>0 //3 '3'|0 //3 ~~'3' //3 ~~'a' ``` <br><br><br> ### ➤轉為布林 利用兩個驚嘆號來得到與數值相對等的布林值 ```javascript !!5 ``` ::: <br> ### <font class="h3">物件的強轉型</font> ==當物件與運算子一起使用時,javascript會把物件都轉為「純值」== ### <font class="h4">➤轉為布林</font> 任何非純質類型的數值,都會被轉為`ture` <br> ### <font class="h4">➤轉為字串與數字</font> :arrow_right:[原始型別包裹物件](https://hackmd.io/@grayshine/ByBiEwRHF) 在將物件轉型為數字與字串時,Javascript根據ECMAScript規範,使用一個叫做ToPrimitive的演算流程,這個流程分別使用`toString`與`valueOf`兩個「預設方法」在所有是物件類型的數值上都可以呼叫,也可以透過複寫來自定。 在ToPrimitive流程裡,當javaScript認為某物件需要被轉為字串,就會==先呼叫`toString`,再呼叫`valueOf`,看哪一個方法在呼叫後能得到純質==,並依之為結果並停止整個流程;反之,在認為需要轉型為數值,或不確定要轉型成哪一個數值時,就先呼叫`valueOf`而後呼叫`toString`。 因此可以概略的這麼說:`toString`影響物件轉為字串的結果,而`valueOf`影響物件轉為數值型別的結果。 :::info 如果宣告一個物件變數,手動`toString()`會得到`[object Object]`字串,這是物件被轉為字串的預設值 ```javascript var a = {} a.toString()//[object Object] ``` 如果用`valueOf`去轉型物件,預設會回傳整個物件本身 ```javascript var a = { name : 'Michael'} a.valueOf()//{ name : 'Michael'} ``` ::: :::info 範例: ```javascript 3+{} //valueOf會先被執行,回傳結果為原物件(並非純值), // 於是會繼續呼叫toString方法,得到3+"[object+Object]" "3[object Object]" //最後會以字串相加方式得到結果 ``` ::: :::info 物件與數字相加的例子,`valueOf`的方法就會被執行而得到數字10 後與3順利相加 ```javascript var a = { valueOf: function(){ return 10 } } a +3 //13 ``` ::: <br> :::info ```javascript []+[] //"" ``` 陣列加陣列等於空字串 ```javascript {}+{} // [object object] ``` ::: ### <font class="h4">物件與非物件(原始型別)比對</font> 當 JavaScript 任意物件在進行 比較運算 時,如 `==` , `!=` , `< `, `<=` , `>` , `>=` 等等,都會先執行 `valueOf()` 或 `toString()` 函式,取回該物件相對應原始型別的值,全看你當下兩邊比較的是甚麼原始型別,然後再進行比較。 :::info ```javascript console.log(10 == [10]);//ture //陣列[10]會轉為數字10 ``` ::: :::info ```javascript console.log('A' == ['A']);//ture ``` ::: ### <font class="h4">物件跟物件對比</font> 在 JavaScript 裡,==所有的物件都是不相等的==,每一個都是獨立的物件實體 (object instance),即便你實作了` valueOf` 或 `toString`方法,還是無法對使用者定義物件進行任何相等比較運算, :::info ```javascript console.log({} == {});//false console.log([] == []);//false ``` 物件與物件比會是false,因為兩個物件的參考位置是不一樣的 <br> ```javascript var n1 = new Number(100); var n2 = new Number(100); n1.valueOf();//100 n1.valueOf();//100 n1 == n2//false ::: --- 參考資料 https://ithelp.ithome.com.tw/articles/10201512 https://blog.miniasp.com/post/2013/07/11/Front-end-Research-JavaScript-valueOf-method

    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