您只需要 Javascript 备忘单!
var、let 和 const 之间的区别
1. var、let 和 const 概述
2. 范围差异
**例子:**
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)
3. 重新申报和重新分配
**例子:**
// 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
4. 提升行为
**例子:**
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;
5. let 和 const 之间的相似之处
6. 何时使用哪个?
7. 提升说明
什么是提升?
提升是 JavaScript 的默认行为,即在编译阶段将声明移动到其范围的顶部。
为什么提升以这种方式工作?
8. 吊装总结
**例子:**
// var console.log(foo); // undefined var foo = 10; // let console.log(bar); // ReferenceError let bar = 20; // const console.log(baz); // ReferenceError const baz = 30;
结论
JavaScript 数据类型
JavaScript 有各种数据类型,分为 **原始** 和 **非原始(引用)** 类型。下面通过示例和差异对每种类型进行解释:
1.原始数据类型
原始类型是不可变的,这意味着它们的值在创建后就无法更改。它们直接存储在内存中。
2. 非原始(引用)数据类型
非原始类型是可变的,并通过引用存储。它们用于存储数据集合或更复杂的实体。
3. 原始类型和非原始类型之间的主要区别
4. 特殊情况
typeof 运算符
动态类型
JavaScript 允许变量在运行时保存不同类型的值:
let value = 10; // Number value = 'Ten'; // String value = true; // Boolean
5. 每种数据类型的示例
原始类型
let str = 'Hello, World'; // String let num = 42; // Number let big = 123456789012345678901n; // BigInt let bool = true; // Boolean let notDefined; // Undefined let emptyValue = null; // Null let uniqueId = Symbol('id'); // Symbol
非原始类型
let obj = { name: 'John', age: 25 }; // Object let arr = [1, 2, 3, 4]; // Array let greet = function () { // Function console.log('Hello'); }; let today = new Date(); // Date let regex = /abc/; // RegExp let map = new Map(); // Map let set = new Set([1, 2, 3]); // Set