最近在上六角學院的js核心篇,將筆記整理出來跟大家分享。
物件的宣告
(推薦)物件實字 Object Literals
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
var family = { property: value, name:'貓貓家', deposit: 500, members:{ big_cat:'大貓貓', small_cat:'小貓貓' }, food:['fish', 'dryFood'], callFamily: function(){ console.log(this) }, callAgain: ()=>{ console.log(this) } }
|
物件建構式
1 2
| var newFamily = new Object(family) newFamily == family
|
物件的取值、新增和刪除
- 取值
family.members
family[‘members’]
使用中括號不只可使用字串方式取值,可以用數字,也可以使用變數方式作取值,甚至在中括號中做運算後再取值
1 2 3
| family['food'][0] let a = 0; family.food[a]
|
- 新增
1 2 3 4
| family.pet='hamster'
family["mouse"] = 'jerry'
|
- 刪除 delete
1 2 3 4 5 6 7 8 9
| delete family.food delete family['food']
name: "貓貓家" deposit: 500 members: {big_cat: "大貓貓", small_cat: "小貓貓"} callFamily: ƒ () callAgain: ƒ ()
|
變數與物件屬性的差異
變數無法被刪除,物件的屬性才可以
1 2 3 4 5 6 7 8 9 10 11
|
var a = 1;
b=2;
delete a; delete b;
console.log(a) console.log(b)
|