【JS】数据结构与操作--数组方法

45 阅读2分钟

技术点清单

技术点目标
map价格展示、格式化商品列表
filter过滤出有效商品/打折商品
reduce计算购物车总价
sort按价格或评分排序商品
some / every检查是否所有商品都符合条件(如库存充足)
数组深拷贝/浅拷贝拷贝购物车数据避免修改原始数据
去重、扁平化、合并数组等算法实现处理分类、标签、商品 ID 列表等
手写实现 map 等方法理解其原理

✅ Step 1:准备商品数据结构

const products = [
  { id: 1, name: "iPhone", price: 6999, discount: 0.9, tags: ["phone", "apple"] },
  { id: 2, name: "Huawei P60", price: 5999, discount: 1, tags: ["phone", "huawei"] },
  { id: 3, name: "AirPods", price: 1299, discount: 0.8, tags: ["accessory", "apple"] },
  { id: 4, name: "iPhone", price: 6999, discount: 0.9, tags: ["phone", "apple"] }, // 重复
];

✅ Step 2:使用 map 显示打折后的价格

const withDiscount = products.map(p => ({
  ...p,
  finalPrice: Math.floor(p.price * p.discount)
}));

✅ Step 3:使用 filter 过滤掉价格超过 6000 的商品

const affordable = withDiscount.filter(p => p.finalPrice <= 6000);

✅ Step 4:使用 reduce 计算购物车总价

const cart = [products[0], products[2]];
const totalPrice = cart.reduce((sum, item) => sum + item.price * item.discount, 0);

✅ Step 5:使用 sort 对商品按最终价格排序

const sorted = [...withDiscount].sort((a, b) => a.finalPrice - b.finalPrice);

✅ Step 6:使用 some / every 判断

const hasDiscount = products.some(p => p.discount < 1);
const allAffordable = products.every(p => p.price < 10000);

✅ Step 7:数组去重(按 id)

const uniqueProducts = Array.from(new Map(products.map(p => [p.id, p])).values());

或手写实现:

function deduplicate(arr) {
  const seen = new Set();
  return arr.filter(item => {
    if (seen.has(item.id)) return false;
    seen.add(item.id);
    return true;
  });
}

✅ Step 8:数组扁平化(标签)

const allTags = products.flatMap(p => p.tags);
// 或手写
function flatten(arr) {
  return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []);
}

✅ Step 9:数组合并(购物车合并)

const cart1 = [products[0]];
const cart2 = [products[2]];
const mergedCart = [...cart1, ...cart2]; // 简单合并

✅ Step 10:浅拷贝 vs 深拷贝

const shallow = [...products]; // 浅拷贝:对象引用相同
const deep = JSON.parse(JSON.stringify(products)); // 深拷贝:彻底复制

✅ Step 11:手写实现 map, filter, reduce

Array.prototype.myMap = function(callback) {
  const res = [];
  for (let i = 0; i < this.length; i++) {
    res.push(callback(this[i], i, this));
  }
  return res;
};

Array.prototype.myFilter = function(callback) {
  const res = [];
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) res.push(this[i]);
  }
  return res;
};

Array.prototype.myReduce = function(callback, initial) {
  let acc = initial ?? this[0];
  for (let i = initial === undefined ? 1 : 0; i < this.length; i++) {
    acc = callback(acc, this[i], i, this);
  }
  return acc;
};