---
# System prepended metadata

title: 物件操作
tags: [ALPHACampWeek1]

---

###### tags: `ALPHACampWeek1`

物件操作
===

typeof判斷型別：這個真的很好用
---
if(typeof(performance[person]) ==='number'){
  	sum+=performance[person]
}   

點記法與標記法
---
// dot notation
myPhone.name // 'myPhone'
// bracket notation
myPhone['name'] // 'myPhone'

列舉出所有的值：for-in 迴圈
---
for (let key in myPhone) {
  console.log(myPhone[key])
}

一口氣取得資料
---
取出所有的 key 值 - Object.keys()
取出所有的 value - Object.values()
取出所有的 pair - Object.entries()

物件導向程式設計
---
const user = {
  name: ['Peter', 'Lee'],
  gender: 'Male',
  age: 41,
  greet: function () {
    console.log(`Hello! I am ${this.name[0]}.`)
  },
  run: function () { console.log('run!')}
}
- 呼叫
user.greet() // Hello! I am Peter.
user.run() // run!

直接將物件當參數
---
如果我現在想要寫一支函式 showDetail() 來印出 user 的所有屬性，以下的方法看起來蠻笨的：

function showDetail(name, gender, age) {
  console.log(`${name[0]} ${name[1]}`)
  console.log(gender)
  console.log(age)
}
showDetail(user.name, user.gender, user.age)

---

更好的方式是直接將物件傳給函式：

function showDetail(user) {
  console.log(`${user.name[0]} ${user.name[1]}`)
  console.log(user.gender)
  console.log(user.age)
}
showDetail(user)

甚至能直接用for-in判斷物件是否為function
function showDetail (user) {
  for (let prop in user) {
    if (typeof user[prop] !== 'function') {
      console.log(user[prop])
    }
  }
}
showDetail(user)

RPG要這樣寫
---
function createPlayer (name, hp, mp) {
  return {
    name: name,
    hp: hp,
    mp: mp
  }
}

const player1 = createPlayer('Magician', 30, 100)
const player2 = createPlayer('Warrior', 100, 30)

console.log(player1) // {name: "Magician", hp: 30, mp: 100}
console.log(player2) // {name: "Warrior", hp: 100, mp: 30}

- 會比這樣寫來的好

當我們需要產生很多個格式相同的物件時，以往我們可能會這樣做：

player1 =  {
  name: 'Magician',
  hp: 30,
  mp: 100
}

player2 =  {
  name: 'Warrior',
  hp: 100,
  mp: 30
}

console.log(player1) // {name: "Magician", hp: 30, mp: 100}
console.log(player2) // {name: "Warrior", hp: 100, mp: 30}