DAY 9
1
Modern Web

## Day09　強制型轉與比較運算子

JavaScript是動態型別`Dynamic Typing`語言，故非常容易發生強制型轉這件事。

``````var a = 1 + 2;
console.log(a)
``````

``````var a = 1 + '2';
console.log(a)
``````

`string`(字串)

``````var a = '1' + '2';
``````

``````var b = 'ithome' + 30;
console.log(b)
``````

console會印出什麼?

`typeof()`來查看一下b現在的型別

`string`(字串)

...不過

``````var c = '10' * 8
console.log(c)
``````

console會印出什麼?

'10'在計算時型別從字串轉型成數值

`number`(數值)

``````var d = '10' - 8
console.log(d)
``````

console會印出什麼?

'10'在計算時型別從字串轉型成數值

`number`(數值)

``````console.log(1 < 2 < 3);
``````

console會印出什麼?

``````console.log(3 < 2 < 1);
``````

console會印出什麼?

`<`相依性為左到右，所以`3 < 2 < 1` 的執行順序是先比較3和2，再比較1。
`3 < 2`相比結果是false，接著再運行`false < 1`的相比較。

`NaN`在JS中表示Not a Number

``````var b = 'ithome' + 30;
console.log(b)
``````

``````var b = 'ithome' - 30;
console.log(b)
``````

``````0 == 0
``````

0與0相等嗎?

``````0 === false
``````

false！

That is going to save your life.

JS是動態語言，會有自動轉型(型轉)的狀況發生，除非我們就是故意要讓它轉換型別來比較、運算，否則進行相等比較時，最好使用===嚴格比較。

JavaScript基礎二三事30