gpt4 book ai didi

javascript - javascript 中的变量行为,使用 += 运算符时旧值不会被覆盖

转载 作者:行者123 更新时间:2023-11-28 18:05:32 24 4
gpt4 key购买 nike

恐怕我的标题没有解释它。我无法理解变量存储某些值时的行为。我会尽力解释我在说什么,

我的代码

<! DOCTYPE html>
<html>
<head>
<title>Current Date and Time</title>
<style>
p { font: 14px normal arial, verdana, helvetica; }
</style>
<script>
function telltime() {
var out = "";
var now = new Date() ;
out += "<br />Date: " + now.getDate() ;
out += "<br />Month: " + now.getMonth() ;
out += "<br />Year: " + now.getFullYear() ;
out += "<br />Hours: " + now.getHours() ;
out += "<br />Minutes: " + now.getMinutes() ;
out += "<br />Seconds: " + now.getSeconds() ;
document.getElementById("div1").innerHTML = out;
}
</script>
</head>
<body>
The current date and time are: <br/>
<div id="div1"></div>
<script>
telltime() ;
</script>
<input type="button" onclick="location.reload() " value="Refresh" />
</body>

输出如下:

First Output

但如果我改变:

  out += "<br />Date: " + now.getDate() ;
out += "<br />Month: " + now.getMonth() ;
out += "<br />Year: " + now.getFullYear() ;
out += "<br />Hours: " + now.getHours() ;
out += "<br />Minutes: " + now.getMinutes() ;
out += "<br />Seconds: " + now.getSeconds() ;

这样:

but if i change:

out = "<br />Date: " + now.getDate() ;
out = "<br />Month: " + now.getMonth() ;
out = "<br />Year: " + now.getFullYear() ;
out = "<br />Hours: " + now.getHours() ;
out = "<br />Minutes: " + now.getMinutes() ;
out = "<br />Seconds: " + now.getSeconds() ;

那么输出将是这样的:

2nd Output

我无法理解这种行为。根据我的理解,如果我们在特定变量中存储新值,则存储在变量中的值总是会被​​覆盖,无论存储该值的方式如何,但在上述情况下, out 存储所有脚本运行时写入的值。但是,如果我们将 += 更改为 =,则 out 仅保留描述当前秒数的最后一个值。

最佳答案

这是因为

out += <br />Date: " + now.getDate()

表示out = out + "<br />Date: " + now.getDate()

其中

out = "<br />Date: " + now.getDate()

分配(并覆盖)output .

更新:

认为我现在明白你陷入困境的地方了。

out = out + <br />Date: " + now.getDate() means out gets a new value which is equal to previous value of out + some new value, so is it not supposed to overwrite the previous value?

如果您问为什么 out 的第二个实例没有也会被覆盖,那么让我解释一下:

out = out + "<br />Date: " + now.getDate()

out =之后将被替换为 out当前时间的值,然后分配给 out .

关于javascript - javascript 中的变量行为,使用 += 运算符时旧值不会被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com