似乎无法让它发挥作用。
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 不是一个函数
请注意,这确实有帮助,但是时间函数是从在 body 负载时启动的函数调用的。
最佳答案
问题是 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);
}
关于JavaScript 使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5628914/