javascript使用全局变量

dga*_*ma3 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);     
 }
Run Code Online (Sandbox Code Playgroud)

错误即时获取是:current_times.getMinutes不是一个函数

请注意这确实有帮助,但时间函数是从一个在身体负载上启动的函数调用的.

Dav*_*ang 5

问题是setMinutes返回一个数字,而不是一个Date对象.

该功能将努力在第一时间你怎么称呼它,但在第二个电话current_times,并future_times会是数字,因此不会有getMinutes作用.由于setMinutes()修改了Date对象而不是生成新对象,因此解决方案是不重新分配变量.


此外,如果我理解您的意图,您的代码可以简化为:

var current_times, future_times = new Date();

function time() {
    current_times = new Date();
    future_times.setMinutes(current_times.getMinutes() + 1);
}
Run Code Online (Sandbox Code Playgroud)