Files
webook/test-notes/编程/JavaScript基础.md
T

65 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# JavaScript 基础
JavaScript 是一种轻量级的解释型编程语言,支持面向对象、命令式和声明式编程。
## 数据类型
JavaScript 有以下几种基本数据类型:
- `Number` - 数字
- `String` - 字符串
- `Boolean` - 布尔值
- `null` - 空值
- `undefined` - 未定义
- `Symbol` - 符号(ES6
- `BigInt` - 大整数
## 代码示例
```javascript
// 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
```javascript
// 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 特性可以让代码更简洁易读。