8.3 JavaScript代码示例
javascript
复制代码
// 现代JavaScript(ES2020+)

// 可选链和空值合并
const user = {
    name: "Alice",
    address: null,
    preferences: {
        theme: "dark"
    }
};

const city = user.address?.city ?? "Unknown";
const theme = user.preferences?.theme ?? "light";

// 解构赋值
const { name, address } = user;
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;

// 箭头函数和函数式编程
const double = x => x * 2;
const isEven = x => x % 2 === 0;
const sum = numbers
    .filter(isEven)
    .map(double)
    .reduce((acc, x) => acc + x, 0);

// 类和继承
class Shape {
    constructor(name) {
        this.name = name;
    }
    
    describe() {
        return `This is a ${this.name}`;
    }
}

class Circle extends Shape {
    constructor(radius) {
        super("circle");
        this.radius = radius;
    }
    
    get area() {
        return Math.PI * this.radius ** 2;
    }
}

// 异步编程(async/await)
async function fetchUserData(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        if (!response.ok) {
            throw new Error(`HTTP error: ${response.status}`);
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Fetch failed:", error);
        throw error;
    }
}

// Promise 组合
const results = await Promise.all([
    fetchUserData(1),
    fetchUserData(2),
    fetchUserData(3)
]);

// 模块系统
export { Circle, fetchUserData };
import { Circle } from './shapes.js';