关于js
JavaScript 是一种动态的、弱类型的解释型语言,最初设计用于浏览器端的交互。
特点
- 轻量级:语法简单,入门门槛低。
- 跨平台:支持在浏览器、Node.js 等多种环境中运行。
- 解释型:无需编译,直接在运行时执行。
- 事件驱动:非常适合处理异步任务,如用户交互、网络请求等。
核心概念
-
变量与数据类型
-
JavaScript 是动态类型语言,可以存储任何类型的数据。
-
变量声明使用
var(老式方式),let(推荐),或const(推荐)。let name = "JavaScript"; // 字符串const version = 2024; // 数字var isCool = true; // 布尔值
-
-
基本数据类型
-
原始类型:
String、Number、Boolean、undefined、null、Symbol、BigInt -
复杂类型:
Object(包括数组、函数等)let array = [1, 2, 3]; // 数组let obj = { key: "value" }; // 对象
-
-
控制流
-
条件语句:
if-else、switch -
循环:
for、while、forEachfor (let i = 0; i < 3; i++) {console.log(i);}
-
-
函数
-
可以定义普通函数或箭头函数。
function greet(name) {return `Hello, ${name}!`;}const greetArrow = (name) => `Hello, ${name}!`;
-
-
事件驱动与异步
-
使用
setTimeout和setInterval定时执行。 -
使用
Promise或async/await处理异步操作。const fetchData = async () => {let response = await fetch("https://api.example.com/data");let data = await response.json();console.log(data);};
-
JS 的运行环境
-
浏览器
-
JavaScript 最初是为浏览器设计,用于动态操作 DOM(网页内容)。
-
示例:点击按钮时弹出提示框。
javascript复制代码document.querySelector("button").addEventListener("click", () => {alert("Button clicked!");});
-
-
Node.js
-
Node.js 是 JavaScript 的服务端运行环境。
-
示例:创建一个简单的 HTTP 服务器。
javascript复制代码const http = require("http");const server = http.createServer((req, res) => {res.end("Hello, Node.js!");});server.listen(3000, () => console.log("Server running at http://localhost:3000"));
-
JavaScript基础
第一章:JavaScript 基础
1.1 变量与常量
- 变量声明方式:
var(不推荐):函数作用域。let(推荐):块作用域,允许重新赋值。const(推荐):块作用域,不允许重新赋值。
示例:
let age = 25;const name = "Alice";console.log(`${name} is ${age} years old.`);- 变量的作用域
- 全局作用域:声明在函数之外,整个程序都可以访问。
- 函数作用域:使用
var声明的变量只在函数内可用。 - 块作用域:使用
let或const声明的变量只在代码块{}内可用。
- 变量提升
var会被提升,但值未赋予时是undefined。let和const不会被提升。
1.2 数据类型
- 基本类型:
String、Number、Boolean、undefined、null、Symbol、BigInt - 复杂类型:
Object(包括数组、函数等)
示例:
let age = 25; // 整数let price = 19.99; // 浮点数let result = "abc" / 2; // NaNlet infinite = 1 / 0; // Infinity
let name = "John";let greeting = `Hello, ${name}!`; // 模板字符串console.log(greeting); // Hello, John!
let isOnline = true;let hasPermission = false;
let x;console.log(x); // undefined
let y = null;console.log(y); // null
let bigNum = 123456789012345678901234567890n;console.log(bigNum); // 123456789012345678901234567890n
let person = { name: "Alice", age: 30,};console.log(person.name); // Alice
let numbers = [1, 2, 3, 4];console.log(numbers[0]); // 1
console.log(typeof 123); // "number"console.log(typeof "hello"); // "string"console.log(typeof true); // "boolean"console.log(typeof undefined); // "undefined"console.log(typeof null); // "object" (这是一个历史遗留问题)console.log(typeof {}); // "object"console.log(typeof []); // "object"
console.log(Array.isArray([])); // trueconsole.log(Array.isArray({})); // false
// 类型转换let str = String(123); // 转为字符串let num = Number("123"); // 转为数字let bool = Boolean(1); // 转为布尔值
console.log("5" + 2); // "52" (字符串拼接)console.log("5" - 2); // 3 (字符串转数字后计算)console.log(true + 1); // 2 (布尔值转为数字)1.3 条件语句
if-else、switch、三元运算符。
示例:
const age = 18;const message = age >= 18 ? "Adult" : "Minor";console.log(message);逻辑运算符
if 条件中经常使用逻辑运算符,结合多个条件判断。
- 逻辑与(&&):所有条件为真时,返回真。
- 逻辑或(||):只要有一个条件为真,返回真。
- 逻辑非(!):将条件取反。
真假值(Truthy 和 Falsy)
JavaScript 中一些值在布尔上下文中会被认为是真或假。
- Falsy(假值):
false、0、""(空字符串)、null、undefined、NaN。 - Truthy(真值):除了 Falsy 以外的所有值。
1.4 循环
for、while、do-while、for...in、for...of
示例:
for (initialization; condition; increment) { // 循环体:在条件为 true 时重复执行的代码}
while (condition) { // 循环体}
do { // 循环体} while (condition);
for (const element of iterable) { // 循环体:每次迭代都会赋值一个元素给 element}
for (const key in object) { // 循环体:每次迭代都会赋值一个属性名给 key}控制循环:break 和 continue
break:退出整个循环。continue:跳过本次循环,直接进入下一次。
第二章:函数与作用域
2.1 函数基础
- 普通函数、函数表达式、箭头函数。
- 默认参数、不定参数。
示例:
const greet = (name = "Guest") => `Hello, ${name}!`;console.log(greet("Alice"));
function greet(name = "Guest") { return `Hello, ${name}!`;}console.log(greet()); // 输出: Hello, Guest!
function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0);}console.log(sum(1, 2, 3, 4)); // 输出: 102.2 作用域与闭包
- 全局作用域、函数作用域、块作用域。
- 全局作用域:在函数之外声明的变量,可以被整个程序访问。
- 函数作用域:在函数内部声明的变量,只能在函数内部访问。
- 块作用域:
let和const声明的变量,只在块{}内可访问。
- 闭包:函数捕获其定义时的作用域变量,通常用于创建私有变量或函数。
示例:
function outerFunction() { let counter = 0; return function () { return ++counter; };}const increment = outerFunction();console.log(increment()); // 1console.log(increment()); // 2
function createMultiplier(multiplier) { return function (value) { return value * multiplier; };}
const double = createMultiplier(2);const triple = createMultiplier(3);console.log(double(5)); // 输出: 10console.log(triple(5)); // 输出: 15第三章:对象与数组
3.1 对象操作
- 创建对象、访问属性、修改属性、删除属性。
- 创建:{},new Object(),class
- 访问:{class}[prop]
- 修改/删除
- 遍历对象:
for...in、Object.keys()、Object.entries()。
示例:
const person = { name: "Alice", age: 25 };console.log(person.name); // Alice
for (const key in person) { console.log(`${key}: ${person[key]}`);}
Object.keys(person).forEach((key) => { console.log(`${key}: ${person[key]}`);});
Object.entries(person).forEach(([key, value]) => { console.log(`${key}: ${value}`);});tips:如果在class中使用()的话:
使用this的时候会调用不了clas内部的属性,这是因为箭头函数 () => {} 的 this 行为与普通函数不同。箭头函数不会创建自己的 this,而是继承自它定义时的外部上下文。
- 箭头函数的
this继承自frunction定义时的作用域。 frunction定义在class对象的上下文中,但箭头函数的this指向的是全局作用域(在浏览器中,this是window;在 Node.js 中是global),而不是person。
因此,this.prop 是未定义的,因为全局作用域中没有 prop 属性。
3.2 数组操作
- 常用方法:
push、pop、map、filter、reduce。push():添加到数组末尾。pop():从数组末尾移除。unshift():添加到数组开头。shift():从数组开头移除。indexOf():找到第一个匹配的索引。includes():检查是否包含某个元素。forEach():对每个元素执行操作。map():返回一个新数组,包含每个元素的处理结果。filter():筛选满足条件的元素。reduce():对数组进行累积计算。
- 解构赋值与展开运算符。
示例:
const numbers = [1, 2, 3];const sum = numbers.reduce((acc, curr) => acc + curr, 0);console.log(sum); // 6
const [a, b, c] = [1, 2, 3];console.log(a, b, c); // 输出: 1 2 3第四章:高级语法与模块化
4.1 解构赋值与展开运算符
- 解构:快速提取数组或对象中的值。
- 展开运算符:快速拷贝或合并对象/数组。
示例:
const [x, , ...z] = [1, 2, 3, 4, 5];console.log(x, z); // 输出: 1 [3,4,5]
const { name, age } = { name: "Alice", age: 25 };console.log(name, age); // Alice 254.2 模板字符串
- 使用反引号(```)动态生成字符串。
示例:
const name = "Alice";console.log(`Hello, ${name}!`);4.3 模块化
- 导出模块:
export和export default。 - 导入模块:
import、import * as。
示例:
export function greet(name) { return `Hello, ${name}!`;}// main.jsimport { greet } from './module.js';console.log(greet("Alice"));tips:
export default默认导出每个模块只有一个,导入时不需要{}。
当使用export * as test from “test.js”时可以直接用test.default
第五章:异步编程
5.1 回调函数
- 异步任务完成时调用回调函数。
示例:
setTimeout(() => console.log("Task complete"), 1000);- 回调地狱
当多个异步任务需要按顺序执行时,嵌套的回调函数会导致代码难以维护,这种现象被称为“回调地狱”。
setTimeout(() => { console.log("Task 1 complete"); setTimeout(() => { console.log("Task 2 complete"); setTimeout(() => { console.log("Task 3 complete"); }, 1000); }, 1000);}, 1000);为了解决回调地狱的问题,可以使用 Promise。
5.2 Promise
-
使用
Promise链式处理异步任务。Promise是一个对象,表示一个异步操作的最终完成或失败。它有以下三种状态:- Pending(进行中):初始状态,未完成或失败。
- Fulfilled(已完成):操作成功,返回结果。
- Rejected(已失败):操作失败,返回错误。
示例:
const promise = new Promise((resolve, reject) => { // 异步操作 if (success) { resolve(value); // 成功时调用 resolve } else { reject(error); // 失败时调用 reject }});
fetch("<https://api.myip.com>") .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error(error));5.3 async/await
async用于声明一个函数,使其返回一个Promise。await用于暂停代码执行,等待Promise解决(resolve)后再继续。
示例:
async function fetchData() { const response = await fetch("<https://api.myip.com>"); const data = await response.json(); console.log(data);}fetchData();
About JavaScript
JavaScript is a dynamic, weakly-typed, interpreted language, originally designed for client-side interactions in the browser.
Features
- Lightweight: Simple syntax, low entry barrier.
- Cross-platform: Runs in multiple environments such as browsers and Node.js.
- Interpreted: No compilation required; executed directly at runtime.
- Event-driven: Very suitable for handling asynchronous tasks, such as user interactions and network requests.
Core Concepts
-
Variables and Data Types
-
JavaScript is a dynamically-typed language and can store values of any type.
-
Variable declarations use
var(old style),let(recommended), orconst(recommended).let name = "JavaScript"; // stringconst version = 2024; // numbervar isCool = true; // boolean
-
-
Primitive Types
-
Primitive types:
String,Number,Boolean,undefined,null,Symbol,BigInt -
Complex types:
Object(including arrays, functions, etc.)let array = [1, 2, 3]; // arraylet obj = { key: "value" }; // object
-
-
Control Flow
-
Conditional statements:
if-else,switch -
Loops:
for、while、forEachfor (let i = 0; i < 3; i++) {console.log(i);}
-
-
Functions
-
Regular functions or arrow functions can be defined.
function greet(name) {return `Hello, ${name}!`;}const greetArrow = (name) => `Hello, ${name}!`;
-
-
Event-driven and Asynchronous
-
Use
setTimeoutandsetIntervalfor timed execution. -
Use
Promiseorasync/awaitto handle asynchronous operations.const fetchData = async () => {let response = await fetch("https://api.example.com/data");let data = await response.json();console.log(data);};
-
JS Runtime Environments
-
Browser
-
JavaScript was originally designed for the browser to dynamically manipulate the DOM (web page content).
-
Example: show a prompt when a button is clicked.
javascript复制代码document.querySelector("button").addEventListener("click", () => {alert("Button clicked!");});
-
-
Node.js
-
Node.js is a server-side runtime for JavaScript.
-
Example: create a simple HTTP server.
javascript复制代码const http = require("http");const server = http.createServer((req, res) => {res.end("Hello, Node.js!");});server.listen(3000, () => console.log("Server running at http://localhost:3000"));
-
JavaScript Basics
Chapter 1: JavaScript Basics
1.1 Variables and Constants
- Variable declaration methods:
var(not recommended): function scope.let(recommended): block scope, allows reassignment.const(recommended): block scope, does not allow reassignment.
Examples:
let age = 25;const name = "Alice";console.log(`${name} is ${age} years old.`);- Variable scope
- Global scope: declared outside of functions, accessible by the entire program.
- Function scope: variables declared with
varare only accessible inside the function. - Block scope: variables declared with
letorconstare only accessible within the code block{}.
- Variable hoisting
varis hoisted, but the value isundefineduntil assigned.letandconstare not hoisted.
1.2 Data Types
- Primitive types:
String,Number,Boolean,undefined,null,Symbol,BigInt - Complex types:
Object(including arrays, functions, etc.)
Examples:
let age = 25; // integerlet price = 19.99; // floatlet result = "abc" / 2; // NaNlet infinite = 1 / 0; // Infinity
let name = "John";let greeting = `Hello, ${name}!`; // template stringconsole.log(greeting); // Hello, John!
let isOnline = true;let hasPermission = false;
let x;console.log(x); // undefined
let y = null;console.log(y); // null
let bigNum = 123456789012345678901234567890n;console.log(bigNum); // 123456789012345678901234567890n
let person = { name: "Alice", age: 30,};console.log(person.name); // Alice
let numbers = [1, 2, 3, 4];console.log(numbers[0]); // 1
console.log(typeof 123); // "number"console.log(typeof "hello"); // "string"console.log(typeof true); // "boolean"console.log(typeof undefined); // "undefined"console.log(typeof null); // "object" (this is a historical quirk)console.log(typeof {}); // "object"console.log(typeof []); // "object"
console.log(Array.isArray([])); // trueconsole.log(Array.isArray({})); // false
// Type conversionlet str = String(123); // to stringlet num = Number("123"); // to numberlet bool = Boolean(1); // to boolean
console.log("5" + 2); // "52" (string concatenation)console.log("5" - 2); // 3 (string to number then calculation)console.log(true + 1); // 2 (boolean to number)1.3 Conditional Statements
if-else,switch, and the ternary operator.
Examples:
const age = 18;const message = age >= 18 ? "Adult" : "Minor";console.log(message);Logical Operators
if conditions often use logical operators to combine multiple conditions.
- Logical AND (&&): true when all conditions are true.
- Logical OR (||): true if any condition is true.
- Logical NOT (!): negates the condition.
Truthy and Falsy Values
In JavaScript, some values evaluate to true or false in boolean contexts.
- Falsy values:
false,0,""(empty string),null,undefined,NaN. - Truthy values: all other values.
1.4 Loops
for,while,do-while,for...in,for...of
Examples:
for (initialization; condition; increment) { // loop body}
while (condition) { // loop body}
do { // loop body} while (condition);
for (const element of iterable) { // loop body}
for (const key in object) { // loop body}Controlling loops: break and continue
break: exit the entire loop.continue: skip the current iteration and proceed to the next one.
Chapter 2: Functions and Scope
2.1 Function Basics
- Regular functions, function expressions, and arrow functions.
- Default parameters and rest parameters.
Examples:
const greet = (name = "Guest") => `Hello, ${name}!`;console.log(greet("Alice"));
function greet(name = "Guest") { return `Hello, ${name}!`;}console.log(greet()); // Output: Hello, Guest!
function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0);}console.log(sum(1, 2, 3, 4)); // Output: 102.2 Scope and Closures
- Global scope, function scope, block scope.
- Global scope: variables declared outside of functions can be accessed by the entire program.
- Function scope: variables declared inside a function are accessible only within that function.
- Block scope: variables declared with
letorconstare only accessible inside the block{}.
- Closures: functions capture the scope variables at the time of their definition, typically used to create private variables or functions.
Examples:
function outerFunction() { let counter = 0; return function () { return ++counter; };}const increment = outerFunction();console.log(increment()); // 1console.log(increment()); // 2
function createMultiplier(multiplier) { return function (value) { return value * multiplier; };}
const double = createMultiplier(2);const triple = createMultiplier(3);console.log(double(5)); // Output: 10console.log(triple(5)); // Output: 15Chapter 3: Objects and Arrays
3.1 Object Operations
- Create objects, access properties, modify properties, delete properties.
- Creation: {}, new Object(), class
- Access: {class}[prop]
- Modify/Delete
- Iterate over objects:
for...in,Object.keys(),Object.entries().
Examples:
const person = { name: "Alice", age: 25 };console.log(person.name); // Alice
for (const key in person) { console.log(`${key}: ${person[key]}`);}
Object.keys(person).forEach((key) => { console.log(`${key}: ${person[key]}`);});
Object.entries(person).forEach(([key, value]) => { console.log(`${key}: ${value}`);});tips: If you use () in a class:
Using this, you may not be able to access the class’s internal properties, because the this behavior of the arrow function () => {} differs from that of a normal function. An arrow function will not create its own this, but inherits it from the outer context in which it is defined.
- Arrow function’s
thisinherits from the scope where the function is defined. - The function is defined in the context of the class object, but the arrow function’s
thispoints to the global scope (in a browser,thisiswindow; in Node.js it’sglobal), and not theperson.
Therefore, this.prop is undefined, because there is no prop property in the global scope.
3.2 Array Operations
- Common methods:
push,pop,map,filter,reduce.push(): adds to the end of the array.pop(): removes from the end of the array.unshift(): adds to the beginning of the array.shift(): removes from the beginning.indexOf(): finds the index of the first matching element.includes(): checks whether an element is contained.forEach(): performs an operation on each element.map(): returns a new array containing the result of processing each element.filter(): filters elements that meet a condition.reduce(): reduces the array to a single value through accumulation.
- Destructuring and spread/rest operators.
Examples:
const numbers = [1, 2, 3];const sum = numbers.reduce((acc, curr) => acc + curr, 0);console.log(sum); // 6
const [a, b, c] = [1, 2, 3];console.log(a, b, c); // Output: 1 2 3Chapter 4: Advanced Syntax and Modularization
4.1 Destructuring and Spread/Rest Operators
- Destructuring: quickly extract values from arrays or objects.
- Spread/rest operators: quickly copy or merge objects/arrays.
Examples:
const [x, , ...z] = [1, 2, 3, 4, 5];console.log(x, z); // Output: 1 [3,4,5]
const { name, age } = { name: "Alice", age: 25 };console.log(name, age); // Alice 254.2 Template Strings
- Use backticks (“) to dynamically generate strings.
Examples:
const name = "Alice";console.log(`Hello, ${name}!`);4.3 Modules
- Exporting modules:
exportandexport default. - Importing modules:
import,import * as.
Examples:
export function greet(name) { return `Hello, ${name}!`;}// main.jsimport { greet } from './module.js';console.log(greet("Alice"));tips:
export default exports a single default export per module; when importing, you don’t need {}.
When using export * as test from “test.js”, you can directly use test.default
Chapter 5: Asynchronous Programming
5.1 Callback Functions
- The callback is invoked when the asynchronous task completes.
Examples:
setTimeout(() => console.log("Task complete"), 1000);- Callback Hell
When multiple asynchronous tasks need to be executed in sequence, nested callbacks can make code hard to maintain; this phenomenon is called “callback hell”.
setTimeout(() => { console.log("Task 1 complete"); setTimeout(() => { console.log("Task 2 complete"); setTimeout(() => { console.log("Task 3 complete"); }, 1000); }, 1000);}, 1000);To solve callback hell, you can use a Promise.
5.2 Promise
-
Use Promises to chain asynchronous tasks.
Promiseis an object that represents the eventual completion or failure of an asynchronous operation. It has three states:- Pending: initial state, not fulfilled or rejected.
- Fulfilled: operation succeeded, returns a result.
- Rejected: operation failed, returns an error.
Examples:
const promise = new Promise((resolve, reject) => { // asynchronous operation if (success) { resolve(value); // call resolve on success } else { reject(error); // call reject on failure }});
fetch("<https://api.myip.com>") .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error(error));5.3 async/await
asyncis used to declare a function that returns aPromise.awaitpauses code execution, waiting for thePromiseto resolve before continuing.
Examples:
async function fetchData() { const response = await fetch("<https://api.myip.com>"); const data = await response.json(); console.log(data);}fetchData();
JavaScript について
JavaScript は動的で、弱い型の解釈型言語で、元々はブラウザ側のインタラクションのために設計されました。
特徴
- 軽量:構文はシンプルで、入門のハードルが低い。
- クロスプラットフォーム対応:ブラウザ、Node.js など、複数の環境で実行可能。
- 解釈型:コンパイル不要、実行時に直接実行。
- イベント駆動:ユーザーインタラクション、ネットワーク要求などの非同期処理の扱いに適している。
コア概念
-
変数とデータ型
-
JavaScript は動的型言語で、あらゆるタイプのデータを格納できます。
-
変数宣言には
var(旧式)、let(推奨)、またはconst(推奨)を使用します。let name = "JavaScript"; // 文字列const version = 2024; // 数字var isCool = true; // ブール値
-
-
基本データ型
-
原始型:
String、Number、Boolean、undefined、null、Symbol、BigInt -
複合型:
Object(配列、関数などを含む)let array = [1, 2, 3]; // 配列let obj = { key: "value" }; // オブジェクト
-
-
制御フロー
-
条件文:
if-else、switch -
ループ:
for、while、forEachfor (let i = 0; i < 3; i++) {console.log(i);}
-
-
関数
-
普通の関数またはアロー関数を定義できます。
function greet(name) {return `Hello, ${name}!`;}const greetArrow = (name) => `Hello, ${name}!`;
-
-
イベント駆動と非同期
-
使用
setTimeoutおよびsetIntervalを用いて定期的に実行。 -
使用
Promiseまたはasync/awaitを用いて非同期処理を処理。const fetchData = async () => {let response = await fetch("https://api.example.com/data");let data = await response.json();console.log(data);};
-
JS の実行環境
-
ブラウザ
-
JavaScript は最初、ブラウザ用に設計され、動的に DOM(ウェブページの内容)を操作します。
-
例:ボタンをクリックしたときにアラートを表示します。
javascript复制代码document.querySelector("button").addEventListener("click", () => {alert("Button clicked!");});
-
-
Node.js
-
Node.js は JavaScript のサーバサイド実行環境です。
-
例:簡単な HTTP サーバーを作成します。
javascript复制代码const http = require("http");const server = http.createServer((req, res) => {res.end("Hello, Node.js!");});server.listen(3000, () => console.log("Server running at http://localhost:3000"));
-
JavaScript基礎
第一章:JavaScript 基礎
1.1 変数と定数
- 変数宣言の方法:
var(推奨されない):関数スコープ。let(推奨):ブロックスコープ、再代入を許可。const(推奨):ブロックスコープ、再代入不可。
例:
let age = 25;const name = "Alice";console.log(`${name} is ${age} years old.`);- 変数のスコープ
- グローバルスコープ:関数の外で宣言され、プログラム全体からアクセス可能。
- 関数スコープ:
varで宣言された変数は関数内でのみ利用可能。 - ブロックスコープ:
letまたはconstで宣言された変数は、ブロック{}内でのみ有効。
- 変数のホイスティング
varはホイスティングされますが、値が代入されていない場合はundefinedになります。letおよびconstはホイスティングされません。
1.2 データ型
- 基本型:
String、Number、Boolean、undefined、null、Symbol、BigInt - 複合型:
Object(配列、関数などを含む)
例:
let age = 25; // 整数let price = 19.99; // 浮動小数点数let result = "abc" / 2; // NaNlet infinite = 1 / 0; // Infinity
let name = "John";let greeting = `Hello, ${name}!`; // テンプレート文字列console.log(greeting); // Hello, John!
let isOnline = true;let hasPermission = false;
let x;console.log(x); // undefined
let y = null;console.log(y); // null
let bigNum = 123456789012345678901234567890n;console.log(bigNum); // 123456789012345678901234567890n
let person = { name: "Alice", age: 30,};console.log(person.name); // Alice
let numbers = [1, 2, 3, 4];console.log(numbers[0]); // 1
console.log(typeof 123); // "number"console.log(typeof "hello"); // "string"console.log(typeof true); // "boolean"console.log(typeof undefined); // "undefined"console.log(typeof null); // "object" (これは歴史的な問題です)console.log(typeof {}); // "object"console.log(typeof []); // "object"
console.log(Array.isArray([])); // trueconsole.log(Array.isArray({})); // false
// 型変換let str = String(123); // 文字列へ変換let num = Number("123"); // 数値へ変換let bool = Boolean(1); // ブール値へ変換
console.log("5" + 2); // "52" (文字列結合)console.log("5" - 2); // 3 (文字列を数値に変換して計算)console.log(true + 1); // 2 (真偽値を数値へ変換)1.3 条件文
if-else、switch、三項演算子。
例:
const age = 18;const message = age >= 18 ? "Adult" : "Minor";console.log(message);論理演算子
if 条件では、複数の条件判断を組み合わせるために論理演算子を頻繁に使用します。
- 論理積(&&):すべての条件が真のとき、真を返します。
- 論理和(||):どれか1つの条件が真であれば、真を返します。
- 論理非(!):条件を反転します。
真偽値(Truthy と Falsy)
JavaScript では、ブール値の文脈で真偽とみなされる値がいくつかあります。
- Falsy(偽値):
false、0、""(空文字列)、null、undefined、NaN。 - Truthy(真値):Falsy 以外のすべての値。
1.4 ループ
for、while、do-while、for...in、for...of
例:
for (initialization; condition; increment) { // ループ本体:条件が true の間、繰り返し実行されるコード}
while (condition) { // ループ本体}
do { // ループ本体} while (condition);
for (const element of iterable) { // ループ本体:各反復で要素を element に代入}
for (const key in object) { // ループ本体:各反復でプロパティ名を key に代入}ループの制御:break と continue
break:全体のループを抜ける。continue:今回のループをスキップし、次の反復へ。
第二章:関数と作用域
2.1 関数の基礎
- 普通の関数、関数式、アロー関数。
- デフォルト引数、可変長引数。
例:
const greet = (name = "Guest") => `Hello, ${name}!`;console.log(greet("Alice"));
function greet(name = "Guest") { return `Hello, ${name}!`;}console.log(greet()); // 出力: Hello, Guest!
function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0);}console.log(sum(1, 2, 3, 4)); // 出力: 102.2 作用域とクロージャ
- グローバルスコープ、関数スコープ、ブロックスコープ。
- グローバルスコープ:関数の外で宣言された変数は、プログラム全体からアクセス可能。
- 関数スコープ:関数内部で宣言された変数は、関数内部でのみアクセス可能。
- ブロックスコープ:
letおよびconstで宣言された変数は、ブロック{}内でのみアクセス可能。
- クロージャ:関数が定義されたときのスコープ変数を捕捉し、通常はプライベート変数や関数を作るのに用いられます。
例:
function outerFunction() { let counter = 0; return function () { return ++counter; };}const increment = outerFunction();console.log(increment()); // 1console.log(increment()); // 2
function createMultiplier(multiplier) { return function (value) { return value * multiplier; };}
const double = createMultiplier(2);const triple = createMultiplier(3);console.log(double(5)); // 出力: 10console.log(triple(5)); // 出力: 15第三章:オブジェクトと配列
3.1 オブジェクト操作
- オブジェクトの作成、属性の参照、属性の変更、属性の削除。
- 作成:{}, new Object(), クラス
- 参照:{class}[prop]
- 変更/削除
- オブジェクトの反復:
for...in、Object.keys()、Object.entries()。
例:
const person = { name: "Alice", age: 25 };console.log(person.name); // Alice
for (const key in person) { console.log(`${key}: ${person[key]}`);}
Object.keys(person).forEach((key) => { console.log(`${key}: ${person[key]}`);});
Object.entries(person).forEach(([key, value]) => { console.log(`${key}: ${value}`);});ヒント:クラス内で () を使用すると、クラス内部の属性を呼び出せなくなることがあります。これは、アロー関数 (() => {}) の this の挙動が通常の関数と異なるためです。アロー関数は自身の this を作成せず、定義時の外部コンテキストから継承します。
- アロー関数の
thisは function 定義時のスコープから継承します。 function定義はclassオブジェクトの文脈にありますが、アロー関数のthisはグローバルスコープを指します(ブラウザではwindow、Node.js ではglobal)、つまりpersonではありません。
したがって、this.prop は未定義になります。グローバルスコープには prop 属性が存在しないためです。
3.2 配列操作
- よく使われるメソッド:
push、pop、map、filter、reduce。 - デストラクチャリングと展開演算子。
例:
const numbers = [1, 2, 3];const sum = numbers.reduce((acc, curr) => acc + curr, 0);console.log(sum); // 6
const [a, b, c] = [1, 2, 3];console.log(a, b, c); // 出力: 1 2 3第四章:高度な文法とモジュール化
4.1 デストラクチャリングと展開演算子
- デストラクチャリング:配列やオブジェクトから値を素早く取り出す。
- 展開演算子:オブジェクト/配列を素早くコピーまたは結合する。
例:
const [x, , ...z] = [1, 2, 3, 4, 5];console.log(x, z); // 出力: 1 [3,4,5]
const { name, age } = { name: "Alice", age: 25 };console.log(name, age); // Alice 254.2 テンプレート文字列
- バッククォート(```)を使用して、動的に文字列を生成する。
例:
const name = "Alice";console.log(`Hello, ${name}!`);4.3 モジュール化
- エクスポート:
exportとexport default。 - インポート:
import、import * as。
例:
export function greet(name) { return `Hello, ${name}!`;}// main.jsimport { greet } from './module.js';console.log(greet("Alice"));ヒント:
export default は各モジュールにつき1つだけの、デフォルトエクスポートであり、インポート時には {} は不要です。
export * as test from "test.js" を使用すると、直接 test.default を使用できます。
第五章:非同期プログラミング
5.1 コールバック関数
- 非同期タスクが完了したときにコールバック関数を呼び出します。
例:
setTimeout(() => console.log("Task complete"), 1000);- コールバック地獄
複数の非同期タスクを順番に実行する必要がある場合、ネストされたコールバックがコードを保守しづらくします。この現象を「コールバック地獄」と呼びます。
setTimeout(() => { console.log("Task 1 complete"); setTimeout(() => { console.log("Task 2 complete"); setTimeout(() => { console.log("Task 3 complete"); }, 1000); }, 1000);}, 1000);この問題を解決するには、Promise を使用します。
5.2 Promise
-
非同期タスクを連鎖して処理するために、
Promiseを使用します。Promiseは、非同期操作の最終的な完了または失敗を表すオブジェクトです。以下の3つの状態があります:- Pending(進行中):初期状態、完了も失敗もしていない。
- Fulfilled(完了):操作が成功し、結果を返す。
- Rejected(失敗):操作が失敗し、エラーを返す。
例:
const promise = new Promise((resolve, reject) => { // 非同期操作 if (success) { resolve(value); // 成功時に resolve を呼ぶ } else { reject(error); // 失敗時に reject を呼ぶ }});
fetch("<https://api.myip.com>") .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error(error));5.3 async/await
asyncは、関数を宣言して、それが返す値をPromiseにする。awaitは、コードの実行を一時停止して、Promiseが解決されるのを待ってから続行する。
例:
async function fetchData() { const response = await fetch("<https://api.myip.com>"); const data = await response.json(); console.log(data);}fetchData();部分信息可能已经过时









