助你精通 JS:函数式 array.forEach 的 8 个实例

2024-12-31 06:41:15   小编

助你精通 JS:函数式 array.forEach 的 8 个实例

在 JavaScript 中,array.forEach 是一个强大且常用的数组方法,它允许我们对数组的每个元素执行特定的操作。下面通过 8 个实例来深入理解它的用法。

实例 1:简单的打印数组元素

let numbers = [1, 2, 3, 4, 5];
numbers.forEach((num) => {
  console.log(num);
});

实例 2:计算数组元素的平方

let nums = [2, 4, 6, 8, 10];
nums.forEach((num) => {
  console.log(num * num);
});

实例 3:将数组元素转换为字符串

let values = [10, 20, 30, 40, 50];
values.forEach((value) => {
  console.log(String(value));
});

实例 4:筛选出奇数元素

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.forEach((num) => {
  if (num % 2!== 0) {
    console.log(num);
  }
});

实例 5:计算数组元素的总和

let numbers2 = [15, 25, 35, 45, 55];
let sum = 0;
numbers2.forEach((num) => {
  sum += num;
});
console.log(sum);

实例 6:修改数组元素的值

let items = [5, 10, 15, 20, 25];
items.forEach((item, index) => {
  items[index] = item * 2;
});
console.log(items);

实例 7:根据条件添加新元素到新数组

let originalArray = [12, 24, 36, 48, 60];
let newArray = [];
originalArray.forEach((num) => {
  if (num > 30) {
    newArray.push(num);
  }
});
console.log(newArray);

实例 8:结合对象数组进行操作

let users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

users.forEach((user) => {
  console.log(`Name: ${user.name}, Age: ${user.age}`);
});

通过以上 8 个实例,相信您对 array.forEach 方法有了更深入的理解和掌握。在实际开发中,灵活运用 array.forEach 可以让我们的代码更加简洁高效。不断实践和探索,您将能够更加熟练地运用 JavaScript 解决各种编程问题。

TAGS: JS 数组操作 JS 函数式编程 JS 实例解析 JS 进阶学习

欢迎使用万千站长工具!

Welcome to www.zzTool.com