// ======================== 数组中的对象 (Array of Objects) ========================
// 定义一个数组 fruits,数组中每个元素都是一个对象
// 每个对象包含 name(名称)、color(颜色)、calories(卡路里)三个属性
const fruits = [
  {name: "apple", color: "red", calories: 95},
  {name: "orange", color: "orange", calories: 45},
  {name: "banana", color: "yellow", calories: 105},
  {name: "coconut", color: "white", calories: 155},
  {name: "pineapple", color: "yellow", calories: 37},
];
 
// ======================== 基本访问 ========================
// 访问第一个水果的卡路里
console.log(fruits[0].calories); // 95
// 访问第三个水果(banana)的名称
console.log(fruits[2].name);     // banana
 
 
// ======================== 添加元素 (push) ========================
// 使用 push() 在数组末尾添加一个新对象
fruits.push({name: "grapes", color: "purple", calories: 62});
console.log(fruits[5]); // 输出新加入的对象:{name: "grapes", color: "purple", calories: 62}
 
 
// ======================== 删除最后一个元素 (pop) ========================
// pop() 会移除数组的最后一个元素
fruits.pop();
console.log(fruits); // 最后一个 "grapes" 被删除
 
 
// ======================== 删除指定位置元素 (splice) ========================
// splice(起始索引, 删除数量)
// 从索引 1 开始删除 3 个元素,即删除 orange、banana、coconut
fruits.splice(1, 3);
console.log(fruits);
// 结果只剩下:[{apple}, {pineapple}]
 
 
// ======================== 遍历数组 (forEach) ========================
// forEach() 会对每个元素执行一次回调函数
// 这里打印每个水果的颜色
fruits.forEach(fruit => console.log(fruit.color));
// 输出:red, yellow
 
 
// ======================== 提取属性 (map) ========================
// map() 会返回一个新数组,保存每个对象中指定的属性值
const fruitNames = fruits.map(fruit => fruit.name);
console.log(fruitNames); // ["apple", "pineapple"]
 
const fruitColors = fruits.map(fruit => fruit.color);
console.log(fruitColors); // ["red", "yellow"]
 
 
// ======================== 条件筛选 (filter) ========================
// filter() 返回一个新数组,包含满足条件的元素
const yellowFruits = fruits.filter(fruit => fruit.color === "yellow");
console.log(yellowFruits); // [{name: "pineapple", color: "yellow", calories: 37}]
 
 
// ======================== 寻找最大值 (reduce) ========================
// reduce() 累计计算数组中的元素
// 这里比较每个水果的卡路里,返回卡路里最高的水果
const maxFruit = fruits.reduce(
  (max, fruit) => fruit.calories > max.calories ? fruit : max
);
console.log(maxFruit); // {name: "apple", color: "red", calories: 95}