JavaScript 数组和对象
数组基础
创建数组
// 字面量语法const fruits = ['apple', 'banana', 'orange'];
// Array 构造函数const numbers = new Array(1, 2, 3, 4, 5);
// Array.from() 方法const characters = Array.from('Hello'); // ['H', 'e', 'l', 'l', 'o']
数组访问和修改
const colors = ['red', 'green', 'blue'];
// 访问元素console.log(colors[0]); // 'red'console.log(colors.length); // 3
// 修改元素colors[1] = 'yellow';console.log(colors); // ['red', 'yellow', 'blue']
常用数组方法
const numbers = [1, 2, 3, 4, 5];
// 添加和删除元素numbers.push(6); // 末尾添加numbers.unshift(0); // 开头添加numbers.pop(); // 删除末尾元素numbers.shift(); // 删除开头元素
// 查找元素const index = numbers.indexOf(3); // 返回元素索引const found = numbers.includes(4); // 检查元素是否存在
// 数组转换const joined = numbers.join(', '); // 转换为字符串const sliced = numbers.slice(1, 4); // 截取部分数组const reversed = numbers.reverse(); // 反转数组
数组遍历
const fruits = ['apple', 'banana', 'orange'];
// forEach 方法fruits.forEach((fruit, index) => { console.log(`${index}: ${fruit}`);});
// map 方法const upperFruits = fruits.map(fruit => fruit.toUpperCase());
// filter 方法const longFruits = fruits.filter(fruit => fruit.length > 5);
// reduce 方法const letters = fruits.reduce((total, fruit) => total + fruit.length, 0);
对象基础
创建对象
// 字面量语法const person = { name: 'Alice', age: 25, sayHello() { console.log('Hello!'); }};
// 构造函数function Person(name, age) { this.name = name; this.age = age;}const bob = new Person('Bob', 30);
访问和修改属性
const user = { name: 'Alice', age: 25, address: { city: 'Beijing', street: 'Main St' }};
// 点号访问console.log(user.name); // 'Alice'console.log(user.address.city); // 'Beijing'
// 方括号访问console.log(user['age']); // 25
// 添加新属性
// 删除属性delete user.age;
对象方法
const book = { title: 'JavaScript Guide', price: 29.99};
// 获取所有键console.log(Object.keys(book)); // ['title', 'price']
// 获取所有值console.log(Object.values(book)); // ['JavaScript Guide', 29.99]
// 获取所有键值对console.log(Object.entries(book)); // [['title', 'JavaScript Guide'], ['price', 29.99]]
// 合并对象const details = { author: 'John Doe' };const fullBook = Object.assign({}, book, details);// 或使用展开运算符const newBook = { ...book, ...details };
解构赋值
数组解构
const numbers = [1, 2, 3, 4, 5];
// 基本解构const [first, second] = numbers;console.log(first, second); // 1, 2
// 跳过元素const [, , third] = numbers;console.log(third); // 3
// 剩余元素const [head, ...tail] = numbers;console.log(head, tail); // 1, [2, 3, 4, 5]
对象解构
const person = { name: 'Alice', age: 25, city: 'Beijing'};
// 基本解构const { name, age } = person;console.log(name, age); // 'Alice', 25
// 重命名const { name: fullName, age: years } = person;console.log(fullName, years); // 'Alice', 25
// 默认值const { country = 'China' } = person;console.log(country); // 'China'
练习
- 创建一个购物车数组,实现添加、删除、计算总价的功能
- 使用对象方法实现一个简单的学生管理系统
- 练习使用数组和对象的解构赋值
小结
- 掌握数组的创建和常用操作方法
- 理解对象的基本概念和属性访问方式
- 熟练使用数组和对象的解构赋值
- 学会使用数组方法进行数据处理
- 掌握对象的高级特性和方法