您只需要 Javascript 備忘單!
var、let 和 const 之間的區別
1. var、let 和 const 概述
Feature | var | let | const |
---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Re-declaration | Allowed within the same scope | Not allowed in the same scope | Not allowed in the same scope |
Re-assignment | Allowed | Allowed | Not allowed after initialization |
Initialization | Can be declared without initialization | Can be declared without initialization | Must be initialized at the time of declaration |
Hoisting | Hoisted but initialized to undefined | Hoisted but not initialized | Hoisted but not initialized |
var
Type | Function Scope | Block Scope |
---|---|---|
var | Variables are scoped to the enclosing function. | Does not support block scope. A var inside a block (if, for, etc.) leaks into the enclosing function or global scope. |
let / const | Not function-scoped. | Variables are confined to the block they are declared in. |
重新聲明
if (true) { var x = 10; let y = 20; const z = 30; } console.log(x); // 10 (accessible because of function scope) console.log(y); // ReferenceError (block-scoped) console.log(z); // ReferenceError (block-scoped)
吊裝
Feature | var | let | const |
---|---|---|---|
Re-declaration | Allowed | Not allowed | Not allowed |
Re-assignment | Allowed | Allowed | Not allowed |
範例:
if (true) { var x = 10; let y = 20; const z = 30; } console.log(x); // 10 (accessible because of function scope) console.log(y); // ReferenceError (block-scoped) console.log(z); // ReferenceError (block-scoped)
4.提升行為
Type | Hoisting Behavior |
---|---|
var | Hoisted to the top of the scope but initialized as undefined. |
let | Hoisted but not initialized. Accessing it before declaration causes a ReferenceError. |
const | Hoisted but not initialized. Must be initialized at the time of declaration. |
提升行為
// Re-declaration var a = 10; var a = 20; // Allowed let b = 30; // let b = 40; // SyntaxError: Identifier 'b' has already been declared const c = 50; // const c = 60; // SyntaxError: Identifier 'c' has already been declared // Re-assignment a = 15; // Allowed b = 35; // Allowed // c = 55; // TypeError: Assignment to constant variable
常數
Feature | let and const |
---|---|
Block Scope | Both are confined to the block in which they are declared. |
No Hoisting Initialization | Both are hoisted but cannot be accessed before initialization. |
Better Practice | Preferred over var for predictable scoping. |
5. let 與 const 之間的相似之處
Scenario | Recommended Keyword |
---|---|
Re-declare variables or use function scope | var (generally avoid unless necessary for legacy code). |
Variables that may change | let (e.g., counters, flags, intermediate calculations). |
Variables that should not change | const (e.g., configuration settings, fixed values). |
7.吊掛說明
什麼是提升?
提升是 JavaScript 在編譯階段將宣告移到其作用域頂端的預設行為。
- var:提升並初始化為未定義。
- let / const:提升但未初始化。這會建立一個從區塊開始到遇到聲明的臨時死區(TDZ)。
為什麼吊掛要這樣運作?
- 編譯階段: JavaScript 首先掃描程式碼為變數和函數宣告建立記憶體空間。在此階段:
- var 變數被初始化為未定義。
- let 和 const 變數被「提升」但未初始化,因此是 TDZ。
- 函數宣告全面提升。
- 執行階段: JavaScript 開始逐行執行程式碼。變數和函數在此階段被賦值。
8.吊掛總結
Type | Hoisting | Access Before Declaration |
---|---|---|
var | Hoisted and initialized to undefined. | Allowed but value is undefined. |
let | Hoisted but not initialized. | Causes a ReferenceError. |
const | Hoisted but not initialized. | Causes a ReferenceError. |
範例:
if (true) { var x = 10; let y = 20; const z = 30; } console.log(x); // 10 (accessible because of function scope) console.log(y); // ReferenceError (block-scoped) console.log(z); // ReferenceError (block-scoped)
結論
- 對於不需要重新賦值的變量,盡可能使用 const。
- 對於需要在相同作用域內重新賦值的變數使用let。
- 避免 var 除非使用遺留程式碼或需要函數範圍的行為。
JavaScript 資料類型
JavaScript 有多種資料類型,分為 原始 和 非原始(參考) 類型。以下是每項的解釋,並附有範例和差異:
1. 原始資料型
原始型別是不可變的,這表示它們的值在建立後就無法變更。它們直接儲存在記憶體中。
Data Type | Example | Description |
---|---|---|
String | "hello", 'world' | Represents a sequence of characters (text). Enclosed in single (''), double (""), or backticks (). |
Number | 42, 3.14, NaN | Represents both integers and floating-point numbers. Includes NaN (Not-a-Number) and Infinity. |
BigInt | 123n, 9007199254740991n | Used for numbers larger than Number.MAX_SAFE_INTEGER (2^53 - 1). Add n to create a BigInt. |
Boolean | true, false | Represents logical values, used in conditions to represent "yes/no" or "on/off". |
Undefined | undefined | Indicates a variable has been declared but not assigned a value. |
Null | null | Represents an intentional absence of value. Often used to reset or clear a variable. |
Symbol | Symbol('id') | Represents a unique identifier, mainly used as property keys for objects to avoid collisions. |
2. 非原始(參考)資料型
非原始類型是可變的並透過引用儲存。它們用於儲存資料集合或更複雜的實體。
Data Type | Example | Description |
---|---|---|
Object | {name: 'John', age: 30} | A collection of key-value pairs. Keys are strings (or Symbols), and values can be any type. |
Array | [1, 2, 3, "apple"] | A list-like ordered collection of values. Access elements via index (e.g., array[0]). |
Function | function greet() {} | A reusable block of code that can be executed. Functions are first-class citizens in JavaScript. |
Date | new Date() | Represents date and time. Provides methods for manipulating dates and times. |
RegExp | /pattern/ | Represents regular expressions used for pattern matching and string searching. |
Map | new Map() | A collection of key-value pairs where keys can be of any type, unlike plain objects. |
Set | new Set([1, 2, 3]) | A collection of unique values, preventing duplicates. |
WeakMap | new WeakMap() | Similar to Map, but keys are weakly held, meaning they can be garbage-collected. |
WeakSet | new WeakSet() | Similar to Set, but holds objects weakly to prevent memory leaks. |
3. 原始類型和非原始類型之間的主要區別
Aspect | Primitive Types | Non-Primitive Types |
---|---|---|
Mutability | Immutable: Values cannot be changed. | Mutable: Values can be modified. |
Storage | Stored directly in memory. | Stored as a reference to a memory location. |
Copy Behavior | Copied by value (creates a new value). | Copied by reference (points to the same object). |
Examples | string, number, boolean, etc. | object, array, function, etc. |
4. 特殊情況
運算子類型
- typeof null:由於 JavaScript 中的歷史錯誤,返回“object”,但 null 不是物件。
- typeof NaN:傳回“數字”,即使它意味著“非數字”。
- typeof function:傳回“function”,它是物件的子類型。
動態打字
JavaScript 允許變數在執行時保存不同類型的值:
if (true) { var x = 10; let y = 20; const z = 30; } console.log(x); // 10 (accessible because of function scope) console.log(y); // ReferenceError (block-scoped) console.log(z); // ReferenceError (block-scoped)
5. 每種資料類型的範例
原型
// Re-declaration var a = 10; var a = 20; // Allowed let b = 30; // let b = 40; // SyntaxError: Identifier 'b' has already been declared const c = 50; // const c = 60; // SyntaxError: Identifier 'c' has already been declared // Re-assignment a = 15; // Allowed b = 35; // Allowed // c = 55; // TypeError: Assignment to constant variable
非原始型
console.log(a); // undefined (hoisted) var a = 10; console.log(b); // ReferenceError (temporal dead zone) let b = 20; console.log(c); // ReferenceError (temporal dead zone) const c = 30;
6. typeof結果總結
Expression | Result |
---|---|
typeof "hello" | "string" |
typeof 42 | "number" |
typeof 123n | "bigint" |
typeof true | "boolean" |
typeof undefined | "undefined" |
typeof null | "object" |
typeof Symbol() | "symbol" |
typeof {} | "object" |
typeof [] | "object" |
typeof function(){} | "function" |
結果
以上是您只需要 Javascript 備忘單!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python和JavaScript開發者的薪資沒有絕對的高低,具體取決於技能和行業需求。 1.Python在數據科學和機器學習領域可能薪資更高。 2.JavaScript在前端和全棧開發中需求大,薪資也可觀。 3.影響因素包括經驗、地理位置、公司規模和特定技能。

實現視差滾動和元素動畫效果的探討本文將探討如何實現類似資生堂官網(https://www.shiseido.co.jp/sb/wonderland/)中�...

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

學習JavaScript不難,但有挑戰。 1)理解基礎概念如變量、數據類型、函數等。 2)掌握異步編程,通過事件循環實現。 3)使用DOM操作和Promise處理異步請求。 4)避免常見錯誤,使用調試技巧。 5)優化性能,遵循最佳實踐。

如何在JavaScript中將具有相同ID的數組元素合併到一個對像中?在處理數據時,我們常常會遇到需要將具有相同ID�...

zustand異步操作中的數據更新問題在使用zustand狀態管理庫時,經常會遇到異步操作導致數據更新不及時的問題。 �...
