2011-04-12 146 views
2

似乎無法得到此工作。JavaScript使用全局變量

var current_times = new Date(); 
var future_times = new Date(); 

function time(){ 
current_times = current_times.setMinutes(current_times.getMinutes()); 
future_times = future_times.setMinutes(future_times.getMinutes() + 1);  
} 

錯誤即時得到的是:current_times.getMinutes不是一個函數

筆記肯定,這會有所幫助,但時間功能是從一個身體上的負荷啓動的函數調用。

+2

有沒有s eem與這段代碼有任何問題。你使用的是什麼瀏覽器?正如我所料,我無法在Chrome中重現該問題。 – 2011-04-12 00:03:41

+1

1.您粘貼的特定代碼有效。 2.不要將Minute設置爲getMinutes()。爲什麼要這麼做?! – Khez 2011-04-12 00:04:19

+1

發佈完整的非工作代碼示例。 – Hamish 2011-04-12 00:06:22

回答

5

問題是setMinutes返回一個數字,而不是Date對象。

該功能在你第一次打電話時會起作用,但第二次打電話時current_timesfuture_times將是數字,因此不會有getMinutes功能。由於setMinutes()修改了Date對象而不是生成新對象,因此解決方法是不要重新分配變量。


而且,如果我正確地理解你的意圖,你的代碼可以簡化爲:

var current_times, future_times = new Date(); 

function time() { 
    current_times = new Date(); 
    future_times.setMinutes(current_times.getMinutes() + 1); 
} 
+0

好,我在想,也許他是在一個命名空間中聲明瞭這些變量並使其全局性無效。 – Khez 2011-04-12 00:11:57

0

的代碼是正確的 但BOX9鍵入代碼

必須分配中的變量功能 就像那樣'

function time() { 
    var current_times = new Date(); 
    var future_times = new Date(); 

    current_times = current_times.setMinutes(current_times.getMinutes()); 
    future_times = future_times.setMinutes(future_times.getMinutes() + 1);  

    document.write(current_times); 
    document.write("<br>"+future_times); 
}