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

您只需要 Javascript 备忘单!

Barbara Streisand
Barbara Streisand原创
2024-12-24 08:20:20555浏览

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