获取Javascript中的变量以动态更改

时间:2014-08-08 21:33:05

标签: javascript variables dynamic

我仍然是Javascript和编程的新手,所以我相信这些问题可以快速解释。这是代码:

此代码计算从现在到上午10点之间的时差,最多可计算864000000,此时它应触发到控制台的日志:It's 10 am

为什么当我console.log(mill2then)时,值仍然是静态的?

然后,当我创建一个动态函数时,理论上应该动态地创建相同的值,我得到一个奇怪的值。我希望它的值是mill2then,大约是663000000,但是我得到了-20069965并且无法确定原因。

var now = new Date();
var then = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0)
var mill2then = then - now;

if (mill2then < 0) {
     mill2then += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){console.log("It's 10am!")}, mill2then);

console.log("Run \n")

console.log("Now's time: " + Date.parse(now))
console.log("The time then: " + Date.parse(then))
console.log("The time to get there:" + mill2then + "\n")

function dynamic(){return new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - new Date()};

var displayDynamic = setInterval(function(){console.log("Why am I not the same as mill2then?: " + dynamic())}, 3*1000)
var displayMill = function(){setInterval(function(){console.log("Here's what the value of mill2then is: " + mill2then)}, 3*1000)};

setTimeout(function(){displayMill()}, 1.5*1000);

3 个答案:

答案 0 :(得分:1)

如果您在上午10点后运行代码,则此代码返回一个负数:

var mill2then = then - now;

然后用这个逻辑进行调整:

if (mill2then < 0) {
  mill2then += 86400000; // it's after 10am, try 10am tomorrow.
}

您在动态功能中没有相同的调整逻辑,因此为负数。

如果您在上午10点之前运行代码,两者都是正数,但只有 mill2then 是静态的(正如MarkM指出的那样。)

答案 1 :(得分:0)

console.log(var)

console.log在您调用它时打印参数所具有的值。更改var的值不会再次调用console.log()。 你会想要做这样的事情:

setInterval(function(){
console.log(var)
},1)

这将打印每毫秒的值,所以如果值会改变,它将被打印后改为毫秒。

当它来到dynamyc函数时,我不确定,尝试在代码中添加some()或只返回计算值。

 function dynamic(){
 var a = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - new Date();
 return a};

答案 2 :(得分:0)

mill2then是静态的。每次通话都不会改变。在第一行中,new Date()的返回值已分配给var now并保持不变 - 它是您第一次拨打电话的日期/时间。

功能dynamic一方面要求每次通话new Date()。你称之为的每一个人都会得到不同的价值。