【问题标题】:How JavaScript compiling sequence works in this code?JavaScript 编译序列如何在这段代码中工作?
【发布时间】:2021-05-30 11:39:55
【问题描述】:

为什么将错误代码行放在底部,运行程序的其余部分。但是放在这里不会运行任何单个函数,会导致错误。

const A = "A";
let F;

function doStuff(B) {
  console.log(B);
  const C = "C";
  let H = "H";
  if (1 + 1 === 2) {
    const D = "D";
    H = "something else";
  }

  console.log(H);
  F = "F";
}

console.log(B); // I know it has error

let E = 0;
while (E < 3) {
  E++;
  console.log(A); //But why this
}
doStuff("B"); // and this
console.log(E); // and this is not working unless I remove that line or place that in the bottom of the code.

【问题讨论】:

  • 我知道它有错误,然后修复它,因为这是问题
  • 听起来你需要研究Javascript scope

标签: javascript node.js reactjs


【解决方案1】:

变量 B 没有在任何地方定义,所以它当然会骂你。

const A = "A";
let F;

function doStuff(B) {
  console.log(B);
  const C = "C";
  let H = "H";
  if (1 + 1 === 2) {
    const D = "D";
    H = "something else";
  }

  console.log(H);
  F = "F";
}

//console.log(B);  <-- What is B, it is not defined anywhere so Javascript will yell at you becasue it doesn't know what it is

let E = 0;
console.log(E); //this works here because E is initialized
while (E < 3) {
  E++;
  console.log(A); //variable A defined at the top of the code can be accessed here so this will work
}
doStuff("B"); // and this
console.log(E); //it will also works here

至于为什么将 console.log(B) 放在底部会运行部分代码,而不是像 C++ 或 C# 那样立即抛出错误,JavaScript 是解释语言,而不是编译语言。这意味着当你运行一段代码时,会有一个解释器会逐行读取每一行代码,然后解释它。 Javascript中根本没有编译步骤。

例如,当浏览器读取第一行,解释它然后运行它时,它仍然会输出“Hello”。它不知道第二行发生了什么

console.log("Hello");
console.log(A)

【讨论】:

  • 我知道 B 没有定义,因此编译器会显示错误,甚至没有打印其他内容。但是如果我将该行放在代码的末尾,它会打印其他内容,然后显示错误。为什么? const A .... let E = 0; while (E &lt; 3) { E++; console.log(A); //Now it works } doStuff("B"); // this also console.log(E); // and this console.log(B); // As it is in the last 为什么把它放在底部,部分运行程序而把它放在上面却不行? JS中是否有特定的编译顺序
  • 你把代码粘贴到chrome devtool中执行了吗?
  • 我在 VS CODE 和一些在线编译器中运行它。如果我按照我在问题ReferenceError: B is not defined 中提出的要求放置线,这就是输出。如果我将线放在底部A A A B something else 3 ReferenceError: B is not defined 这些是输出。为什么它正在执行其他事情然后显示错误,而不是全部显示在上面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多