1.3 KiB
1.3 KiB
JavaScript 基础
JavaScript 是一种轻量级的解释型编程语言,支持面向对象、命令式和声明式编程。
数据类型
JavaScript 有以下几种基本数据类型:
Number- 数字String- 字符串Boolean- 布尔值null- 空值undefined- 未定义Symbol- 符号(ES6)BigInt- 大整数
代码示例
// Hello World
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('World'));
// 箭头函数
const add = (a, b) => a + b;
console.log(add(1, 2)); // 3
Promise 和 async/await
// Promise 示例
function fetchData(url) {
return fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
// async/await 写法
async function fetchDataAsync(url) {
try {
const response = await fetch(url);
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
数组方法
| 方法 | 描述 | 返回值 |
|---|---|---|
map() |
映射每个元素 | 新数组 |
filter() |
过滤元素 | 新数组 |
reduce() |
累加计算 | 单个值 |
forEach() |
遍历元素 | undefined |
提示: 使用现代 JavaScript 特性可以让代码更简洁易读。