在 JavaScript 中宣告和初始化變數有什麼區別?


以下內容陳述了 ECMAScript 規範中關於宣告和初始化變數的內容 -

A var statement declares variables that are scoped to the running execution context’s VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created. [...] A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer’s AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.

以上定義了兩者的區別

  • 所有變數都初始化為 undefined。
  • 變數宣告在初始化其詞法環境時初始化為 undefined。
  • 此初始化不作為賦值使用。

更新於: 2020 年 6 月 13 日

436 次瀏覽

啟動你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.