javascript - 为什么+"the number is"之前有x

标签 javascript

<!DOCTYPE html>
<html>
<body>

<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction() {
  var x = "";
  for ( var i = 0; i < 5; i++ ) {
      x = x + "The number is " + i + "<br>";
  }
  document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

我理解它返回的内容,但我不理解每个语句之前的 x。

x = x + "The number is " + i + "<br>";

最佳答案

x 是一个变量,它将在循环中增长。

行:

x = x + "The number is " + i + <br>

仅附加行 “数字是” + i + 行尾 到 x 的当前值。

将此行视为:

var y = x + "The number is " + i + <br>
x = y

在循环结束时,x 值得:

“数字是0
数字是1
数字是2
数字是3
数字是4

如果不是 x = "",而是 x = "Hello, ",那么最终结果将是:

“您好,号码是0
号码是1
号码是2
号码是3
号码是4

关于javascript - 为什么+"the number is"之前有x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14674327/

相关文章:

javascript - 新日期(毫秒)返回无效日期

javascript - 如何在 chrome 扩展中匹配 youtube 的 url?

javascript - 将 dojo 工具提示对话框添加到每个表格单元格

javascript - 节点列表中 for 的意外行为

javascript - 使用 HOC 返回的组件将属性传递给组件会导致错误

Javascript - 将变量添加到表单提交中

javascript - 对 chrome 和其他浏览器的 react

javascript - 遍历json对象并根据键名将子obj属性移动到父对象

javascript - 如何使用 jQuery next 函数跳过 span 元素?

javascript - 使用数组中的多个值范围填充 html 表