为什么代码执行结果是10? JS语法

发布于 2025-01-12 02:24:19 字数 152 浏览 0 评论 0原文

代码为:

x = 10;

if (x > 1) {
  var x = x + 1;
}

console.log(x);
var x;

代码执行的输出为: 11

为什么是11? ,为什么它不是一个错误?

The code is:

x = 10;

if (x > 1) {
  var x = x + 1;
}

console.log(x);
var x;

The output of code execution is: 11

Why is it 11? , And Why is it not an error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神仙妹妹 2025-01-19 02:24:19

描述

var 声明,无论出现在何处,都会在任何代码之前进行处理
被执行。这称为提升,将在下面进一步讨论。

https://developer.mozilla.org/ en-US/docs/Web/JavaScript/Reference/Statements/var#description

这意味着“var x”在哪里并不重要,当处理此脚本时,声明将是第一个。

Description

var declarations, wherever they occur, are processed before any code
is executed. This is called hoisting and is discussed further below.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#description

This means it does not matter where is your "var x", when this script is processed, the declaration will be the first.

甜警司 2025-01-19 02:24:19

您应该了解闭包实际上是如何工作的。

// You define 'x' variable [1] in global scope 
x = 10;


if (x > 1) {
  // You define another one 'x' variable inside of 'if' scope
  // So here (inside of 'if') you will interact with this variable,
  // not with first one ([1])
  var x = x + 1;
}

// You code run out of 'if' so you're working with 
// global scope again, and your 'x' is first one [1]
console.log(x); // x = 10 still 
var x;

You should understand how closures actually work.

// You define 'x' variable [1] in global scope 
x = 10;


if (x > 1) {
  // You define another one 'x' variable inside of 'if' scope
  // So here (inside of 'if') you will interact with this variable,
  // not with first one ([1])
  var x = x + 1;
}

// You code run out of 'if' so you're working with 
// global scope again, and your 'x' is first one [1]
console.log(x); // x = 10 still 
var x;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文