2012-07-13 31 views
0

我剛剛在學校學習對象,我知道函數可以從對象內部運行,但函數實際上被稱爲方法,我的方法有一個數組,我喜歡通過改變全局變量來獲取一個特定的目標在console.log中觸發。這可以做到嗎?我得到的所有未定義在最後一個console.log - > ing在「+ worker.getLocation.myLocation);所以在所有現實中,我試圖改變全局變量,var myLocation = 0以輸出不同的myLocation的getLocation方法。從對象的方法內的數組中運行console.log

var myLocation = 0 

var worker = { 
    realName:  "Willson", 
    title:   "Assistant Maintenance Supervisor", 
    maintenance: true, 
    vehicals:  ["2008 Dodge Caliber SRT-4", "2012 Jeep Wrangler Unlimited"  ], 
    getLocation: function() { 
     myLocation [0] = "Villas at Sunrise Mountain"; 
     myLocation [1] = "Reno Villas"; 
     myLocation [2] = "lost"; 
     myLocation [3] = "back home"; 
    } 
}; 

console.log(worker.realName + " is a " + worker.title + " and drives a " + worker.vehicals[1] + " to work."); 

var destination = { 
    property: ["Villas at Sunrise Mountain", "Reno Villas", "lost", "back home"] 
}; 

console.log ("He sold his " + worker.vehicals[0] + "." + " Today he is working at " + worker.getLocation.myLocation); 
+0

初始化'myLocation'爲使用托架符號陣列,'[]',因爲我看到要添加的元素到它,就好像它是。 – 0x499602D2 2012-07-13 21:36:33

+0

啊是謝謝。 – Ezcaflowne 2012-07-13 21:47:20

回答

1
var myLocation = 0 

var worker = { 
    realName:  "Willson", 
    title:   "Assistant Maintenance Supervisor", 
    maintenance: true, 
    vehicals:  ["2008 Dodge Caliber SRT-4", "2012 Jeep Wrangler Unlimited"  ], 
    getLocation: function() { 
     var myLocationss = []; 
     myLocationss [0] = "Villas at Sunrise Mountain"; 
     myLocationss [1] = "Reno Villas"; 
     myLocationss [2] = "lost"; 
     myLocationss [3] = "back home"; 

     return myLocations[myLocation]; 

    } 
}; 

console.log(worker.realName + " is a " + worker.title + " and drives a " + worker.vehicals[1] + " to work."); 

var destination = { 
    property: ["Villas at Sunrise Mountain", "Reno Villas", "lost", "back home"] 
}; 

console.log ("He sold his " + worker.vehicals[0] + "." + " Today he is working at " + worker.getLocation()); 
+0

謝謝你flylies我知道這是我需要改變的一點點。 – Ezcaflowne 2012-07-13 21:46:14

+0

不客氣! – 2012-07-13 21:47:02

相關問題