var school = { name:'Taipei University', age:45, vacation:true, teacher:['Mike','Lisha','Bob'], classes: { student:['Kevin','Clara','Rose'], }, broadcast:function(){ console.log('學校廣播'); } }
物件取值
在 JS有兩種方法可以獲得物件中的值:
使用 . 點運算子
使用中刮號 []
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var school = { name:'Taipei University', age:45, vacation:true, teacher:['Mike','Lisha','Bob'], classes: { student:['Kevin','Clara','Rose'], }, broadcast:function(){ console.log('學校廣播'); } } school.name //Taipei University school['age'] //45
使用 [] 方法取值,有個好處,是可以透過變數替換 [] 中的值,來取出物件中不同的值,也就是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var school = { name:'Taipei University', age:45, vacation:true, teacher:['Mike','Lisha','Bob'], classes: { student:['Kevin','Clara','Rose'], }, broadcast:function(){ console.log('學校廣播'); } } var test ='name' console.log(school[test]) // Taipei University test = 'age' console.log(school[test]) // 45