您只需要 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.影响因素包括经验、地理位置、公司规模和特定技能。

学习JavaScript不难,但有挑战。1)理解基础概念如变量、数据类型、函数等。2)掌握异步编程,通过事件循环实现。3)使用DOM操作和Promise处理异步请求。4)避免常见错误,使用调试技巧。5)优化性能,遵循最佳实践。

实现视差滚动和元素动画效果的探讨本文将探讨如何实现类似资生堂官网(https://www.shiseido.co.jp/sb/wonderland/)中�...

如何在JavaScript中将具有相同ID的数组元素合并到一个对象中?在处理数据时,我们常常会遇到需要将具有相同ID�...

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

深入探讨console.log输出差异的根源本文将分析一段代码中console.log函数输出结果的差异,并解释其背后的原因。�...
