一、数组的遍历方法

forEach:单纯遍历

const nums = [1, 2, 3];
nums.forEach((n) => {
  console.log(n);
});

map:映射成新数组

map 会把每个元素处理一遍,返回一个长度相同的新数组,原数组不变。

const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);
console.log(doubled);   // [2, 4, 6]

filter:按条件筛选

const nums = [1, 2, 3, 4, 5, 6];
const evens = nums.filter((n) => n % 2 === 0);
console.log(evens);     // [2, 4, 6]

reduce:累计成一个值

const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum);       // 10

find:找到第一个符合条件的元素

const users = [{ name: "建建" }, { name: "小明" }];
const target = users.find((u) => u.name === "小明");
console.log(target);    // { name: '小明' }

二、对象的遍历

对象不能直接用 forEach,一般用 Object.keys、Object.values、Object.entries 转成数组再处理。

const user = { name: "建建", age: 22, city: "成都" };

Object.keys(user).forEach((key) => {
  console.log(key, user[key]);
});

// 键值对一起遍历
Object.entries(user).forEach(([key, value]) => {
  console.log(key, "=", value);
});

三、解构赋值

数组解构

const arr = [10, 20, 30];
const [a, b] = arr;
console.log(a, b);      // 10 20

对象解构

const user = { name: "建建", age: 22 };
const { name, age } = user;
console.log(name, age); // 建建 22

// 也可以重命名
const { name: nickname } = user;
console.log(nickname);  // 建建

四、展开运算符 ...

展开运算符可以快速复制、合并数组或对象。

const a = [1, 2];
const b = [3, 4];
console.log([...a, ...b]);          // [1, 2, 3, 4]

const user = { name: "建建" };
const more = { ...user, age: 22 };
console.log(more);                  // { name: '建建', age: 22 }
小提醒:map / filter / reduce 都不会修改原数组,是"函数式"的写法;如果只想得到处理后的结果,优先用它们,比手写 for 循环更清晰。

五、小结