Try   HackMD

型別有哪些?該如何操作?

本篇會談到

  • 「型別」的區分
  • 各種型別操作

「型別」的區分

型別可以分為兩大類:


number 數字

數字型別第一個數字不會有 0

let a = 0912345678; console.log(a); // 912345678 // 注意:數字型別沒有前置零 let b = 0.912345678; console.log(b); // 0.912345678 let c = 0; console.log(c); // 0

Symbol 獨一無二的值

ES6 新的一種基本資料型態

  • Symbol 值透過 Symbol() 函數來生成

    ​​​​let s1 = Symbol(); ​​​​let s2 = Symbol(); ​​​​s1 === s2; ​​​​// false ​​​​// 因為是獨一無二的
  • Symbol() 是一個函數,不能用 new 去建立

    ​​​​let s = new Symbol(); ​​​​// TypeError: Symbol is not a constructor

各種型別操作

typeof 檢測資料型別

使用 typeof 查詢資料型別,所回傳的值會是字串型別

利用 typeof 來看是什麼型別!

  • typeof 的回傳值有:string boolean number object undefined function
  • 特別注意
    • null 是 (object),JS 在剛開始就是設定這個 type
    • [1, 2, 3] 是 (object),在JS裡面 type 沒有 Array
typeof 'Hello World!'; // 'string' 字串 typeof true; // 'boolean' 布林 typeof 1234567; // 'number' 數字 typeof null; // 'object' 物件 typeof undefined; // 'undefined' typeof { name: 'Jack' }; // 'object' typeof Symbol(); // 'symbol' typeof function() {}; // 'function' typeof [1, 2, 3]; // 'object' typeof NaN; // 'number' 數字 // NaN 是無效的數字,所以用 typeof 來看是數字型別 // NaN 與任何數字運算都會得到 NaN,並且 NaN 不大於、不小於也不等於任何數字,也不包含 NaN 本身

parseInt() 字串轉數字

  • 語法: parseInt(string,radix)
    • string
      欲轉換的值。若第一個參數值的類型不是 String,會先使用 toString() 轉換成字串
    • radix
      進位系統
  • 使用情境:想將字串變成數字運算時
  • 使用方式:
    ​​​​let a = "123"; ​​​​a = parseInt(a); ​​​​console.log(a)// 回傳 123 ​​​​ ​​​​parseInt("1A34") // 回傳 1 ,A 無法被解析為數字,所以停止解析
  • 第一個數值無法被解析,直接回傳 NaN。例如"你很棒"、""空值,會回傳NaN*

toString() 數字轉字串

  • 使用情境:想將數字變成字串時,例如需要電話號碼連號,不希望去運算
    • 使用方式:
    ​​​​let a = 091234567; ​​​​a = a.toString(); ​​​​console.log(a) ​​​​// "91234567" ​​​​typeof a; ​​​​// string

Number() 針對各類型數字進行轉換

  • 較為嚴格,當轉換值中包含無法轉換的內容時,會直接回傳 NaN。
tags: JS

最後,親愛的大家!我需要你的大聲鼓勵 ٩(⚙ᴗ⚙)۶

如果覺得這篇文章對你有幫助,請給我個一個小小的鼓勵 ❤ 讓我知道,這會成為我寫下去很大的動力。
對了,我還有其他文章,如果有興趣也來逛逛吧!
(文章中如有覺得不妥之處、錯誤內容,也可以透過聯絡我,我會儘速改善,感謝!)

☞ YoJanni 珍妮 2021 正在設計轉職前端的路上,希望大家在學習的路上能夠一起成長
☞ 聯絡我