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中文网其他相关文章!

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Atom编辑器mac版下载
最流行的的开源编辑器