資料型別與運算符號


Posted by ericcch24 on 2020-07-11

資料型別

  • 可以用 typeof 來判斷型態

    *註:其中'Boolean', 'Number', 'String' 三種原始類型合稱為'Primitive'
  • 當字串跟數字「比大小」的時候,會被轉成數字來比較
  • 當字串 + 數字的時候,不會數字相加,而是直接合併
    例如:1 + '3' = 13

物件

例如當我把資料存取成陣列,但陣列的一個元素裡面又有 1 個以上的以元素時,可以改用物件來存取。

  • EX: LIOJ1033
  • 輸入的每一行資料都代表平面座標的 (x, y) 點
    input:
    2 2
    1 1
    10 10
    100 100
let dots = []
for (let i = 1; i < lines.length; i++) {
  let temp = lines[i].split(' ')
  dots.push ({
    x: Number(temp[0]), 
    y: Number(temp[1])
  })

  // dot => [
  // { x: 2, y: 2 },
  // { x: 1, y: 1 },
  // { x: 10, y: 10 },
  // { x: 100, y: 100 }
  // ]
}
  • 讀取物件內容

    • 操作物件時,你需要透過它的 key 來存取物件的屬性。這在寫法上有兩種方式:

      Dot notation
      Bracket notation
      兩種方式的範例分別如下:

// dot notation
flashcardEntry.word
// bracket notation
flashcardEntry['word']

* 如果使用 dot notation,表示你在呼叫物件的屬性,或者可以說,你在呼叫 flashcardEntry 物件的 word 方法 ;如果使用 bracket notation,意義比較像你使用 'word' 這個 key 想取出 flashcardEntry 的內容。

比較運算

  • 設置條件時,只用 ===,不要用==,例如`
if (score === 100){
  console.log('good')
  }`

比較運算子有時候會遇到不同型別要「自動轉型」的狀況,規則大致如下:

  • 兩者都是數字,則單純就其字面大小比較。
  • 如果其中一個是數字,而另一個不是,則會嘗試在背後將另一個先轉為數字後再比較。
  • 如果兩者都是字串,則會依照字母的順序 (standard lexicographical ordering) 來進行比較。[註1] 實戰題:LIOJ1004
  • 如果其中一者是 boolean 的情況,則會把 true 看成 1false 看成 0 再進行比較。
  • 如果是物件的情況下,則是會先透過物件的 valueOf()方法先求得對應的數值,若物件沒有 valueOf() 方法的話,則會透過toString()`` 轉型再進行比較。
  • [註1]:standard lexicographical ordering:簡單來說,字串的順序可以想像成「英語字典」中的單字,第一個字母、以 a、b、c ... 到 z 的順序排列;如果第一個字母一樣,那麼比較第二個、第三個乃至後面的字母。需要注意的是,大小寫字母 unicode 裡的順序是不一樣的。
  • 參考資料

  • 當宣告一個變數是一個物件時,會將物件放置於某個記憶體位置,因此當兩個值相等的物件或陣列時,經 js 判斷後並不相等,因為他們指向的記憶體位置並不相同。下圖的值皆為 false
  • Ex1:

    ```
    var obj = {
    a: 1
    }

var obj2 = obj
obj2.a = 2

console.log(obj === obj2)


**此段回傳值是 true,因為 obj, obj2 指向同一個記憶體位置,因此改變 obj2 的 a 值會連 obj 的也一起改成 2,兩者判斷還是一樣**

* Ex2:

var obj = {
a: 1
}

var obj2 = obj
obj2.a = 2
obj2 = {
b: 1
}

console.log(obj === obj2)


**此段回傳值是 false,因為 obj2 已經被賦予一個新的物件,指向的記憶體位置就會改變,就跟 obj 不一樣了。**
![](https://i.imgur.com/Tl4cpAk.png)
* 參考資料:[從博物館寄物櫃理解變數儲存模型](https://medium.com/@hulitw/variable-and-frontdesk-a53a0440af3c)
-----
## 邏輯運算
![](https://i.imgur.com/GWZVXmO.png)
* Ex:

30 || 6 >> 30
6 || 30 >> 6
6 && 30 >> 30
30 && 6 >> 6
0 || 30 >> 30
30 || 0 >> 30
0 && 30 >> 0
30 && 0 >> 0
0 || 0 >> 0
0 && 0 >> 0
```


特殊運算


賦值運算


#WeeK2







Related Posts

Elevate Your Dermatology Practice with the Electric Dermatology Chair

Elevate Your Dermatology Practice with the Electric Dermatology Chair

自駕車 Sensor Fusion in Visual Perception 簡介

自駕車 Sensor Fusion in Visual Perception 簡介

000|AskYou3000 提問清單

000|AskYou3000 提問清單


Comments