Javascript 類型轉換 Number( ) parseInt( )

Number( )
可以將其他的類型轉換成number

字串裡面是一個合法的數字,則轉換對應的數字
字串裡面是空白,則轉換成數字0

留意以下狀況!!
字串裡面不是合法的數字,則轉換為NaN
null,則轉換為0
undefined,則轉換為NaN

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let a = "123";
a = Number(a);

let b = "english";
b = Number(b);

let c = "32px";
c = Number(c);

let d = " ";
d = Number(d);

let e = true;
e = Number(e);

let f = null;
f = Number(f);

let g = undefined;
g = Number(g);

console.log(a, typeof b, b, c, d, e, f, g);

//輸出 123 "number" NaN NaN 0 1 0 NaN

接續來介紹,類似但是結果不同
parseInt( )
將字串轉換成一個整數
parseInt解析的時候,從左至右讀取字串,直到讀取字串裡面所有的整數
字串的左邊第一個不是數字,則轉換為NaN

1
2
3
4
5
let a = "32px";
a = parseInt(a);
console.log(a, typeof a);

//輸出 32 "number"
1
2
3
4
5
let b = "3.14159265359";
b = parseInt(b);
console.log(b, typeof b);

//輸出 3 "number"
1
2
3
4
5
let c = "hello77";
c = parseInt(c);
console.log(c, typeof c);

//輸出 NaN "number"

參考mdn文件
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number