2011-04-12 132 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); 
}