繁体   English   中英

javascript使用全局变量

[英]javascript using global variables

似乎无法使它正常工作。

 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不是一个函数

请注意,这肯定会有所帮助,但是时间函数是从人体负荷启动的函数中调用的。

问题是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);
}

该代码是正确的,但作为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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM