首页 web前端 js教程 您只需要 Javascript 备忘单!

您只需要 Javascript 备忘单!

Dec 24, 2024 am 08:20 AM

Only Javascript cheatsheet you need !

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)
登录后复制
登录后复制
登录后复制
登录后复制
无需初始化即可声明 无需初始化即可声明 必须在声明时初始化
吊装

已提升但初始化为未定义 已提升但未初始化 已提升但未初始化 表>
2.范围差异
Feature var let const
Re-declaration Allowed Not allowed Not allowed
Re-assignment Allowed Allowed Not allowed
类型 函数范围 块范围 标题> var 变量的作用域为封闭函数。 不支持块作用域。块内的 var(if、for 等)会泄漏到封闭函数或全局作用域中。 let / const 不是函数范围的。 变量仅限于声明它们的块内。 表> 示例: 3.重新声明和重新分配 功能 var 让 常量 标题> 重新声明 允许 不允许 不允许 重新分配 允许 允许 不允许 表>

示例:

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.
类型

提升行为

标题> var
提升到范围顶部,但初始化为未定义。 让
// 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).
功能 let 和 const 标题> 块范围 两者都仅限于声明它们的块。 无提升初始化 两者都被提升,但在初始化之前无法访问。 更好的实践 在可预测范围方面优于 var。 表> 6.何时使用哪个? 场景 推荐关键字 标题> 重新声明变量或使用函数作用域 var(除非遗留代码需要,否则通常避免使用)。 可能改变的变量 let(例如计数器、标志、中间计算)。 不应更改的变量 const(例如配置设置、固定值)。 表>

7.吊装说明

什么是提升?

提升是 JavaScript 在编译阶段将声明移动到其作用域顶部的默认行为。

  • var:提升并初始化为未定义。
  • let / const:提升但未初始化。这会创建一个从块开始到遇到声明的临时死区(TDZ)

为什么吊装要这样工作?

  1. 编译阶段: JavaScript 首先扫描代码为变量和函数声明创建内存空间。在此阶段:
  • var 变量被初始化为未定义。
  • let 和 const 变量被“提升”但未初始化,因此是 TDZ。
  • 函数声明全面提升。
  1. 执行阶段: 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.
类型 吊装 声明前访问 标题> var 提升并初始化为未定义。 允许,但值未定义。 让 已提升但未初始化。 导致引用错误。 常量 已提升但未初始化。 导致引用错误。 表>

示例:

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)
登录后复制
登录后复制
登录后复制
登录后复制

结论

  1. 对于不需要重新赋值的变量,尽可能使用 const
  2. 对于需要在同一作用域内重新赋值的变量使用let
  3. 避免 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.
数据类型 示例 描述 标题> 字符串 “你好世界' 表示字符序列(文本)。用单引号 ('')、双引号 ("") 或反引号 () 括起来。 数字 42, 3.14, 南 表示整数和浮点数。包括 NaN(非数字)和无穷大。 BigInt 123n, 9007199254740991n 用于大于 Number.MAX_SAFE_INTEGER (2^53 - 1) 的数字。添加 n 创建一个 BigInt。 布尔值 真,假 表示逻辑值,用于条件中表示“是/否”或“开/关”。 未定义 未定义 表示变量已声明但未赋值。 空 空 表示故意缺少值。通常用于重置或清除变量。 符号 符号('id') 表示唯一标识符,主要用作对象的属性键,避免碰撞。 表>

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"
表情
结果 标题> 类型“你好” “字符串” 类型42 “数字” 类型123n “bigint” 类型为true “布尔值” 类型未定义 “未定义” 类型为空 “对象” 符号类型() “符号” 类型{} “对象” 类型[] “对象” typeof 函数(){} “功能” 表>

以上是您只需要 Javascript 备忘单!的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

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

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

前端热敏纸小票打印遇到乱码问题怎么办? 前端热敏纸小票打印遇到乱码问题怎么办? Apr 04, 2025 pm 02:42 PM

前端热敏纸小票打印的常见问题与解决方案在前端开发中,小票打印是一个常见的需求。然而,很多开发者在实...

神秘的JavaScript:它的作用以及为什么重要 神秘的JavaScript:它的作用以及为什么重要 Apr 09, 2025 am 12:07 AM

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

谁得到更多的Python或JavaScript? 谁得到更多的Python或JavaScript? Apr 04, 2025 am 12:09 AM

Python和JavaScript开发者的薪资没有绝对的高低,具体取决于技能和行业需求。1.Python在数据科学和机器学习领域可能薪资更高。2.JavaScript在前端和全栈开发中需求大,薪资也可观。3.影响因素包括经验、地理位置、公司规模和特定技能。

JavaScript难以学习吗? JavaScript难以学习吗? Apr 03, 2025 am 12:20 AM

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

如何实现视差滚动和元素动画效果,像资生堂官网那样?
或者:
怎样才能像资生堂官网一样,实现页面滚动伴随的动画效果? 如何实现视差滚动和元素动画效果,像资生堂官网那样? 或者: 怎样才能像资生堂官网一样,实现页面滚动伴随的动画效果? Apr 04, 2025 pm 05:36 PM

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

如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? 如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? Apr 04, 2025 pm 05:09 PM

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

JavaScript的演变:当前的趋势和未来前景 JavaScript的演变:当前的趋势和未来前景 Apr 10, 2025 am 09:33 AM

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

console.log输出结果差异:两次调用为何不同? console.log输出结果差异:两次调用为何不同? Apr 04, 2025 pm 05:12 PM

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

See all articles