liany920

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

JavaScript 中的数组方法(不完全指南)

  1. map
    用途
    map 方法用于对数组中的每个元素执行某种操作,并返回一个新数组,新数组的每个元素是原数组元素经过操作后的结果。
    const numbers = [1, 2, 3, 4]; const squared = numbers.map(num => num * num); // [1, 4, 9, 16]
  2. forEach
    用途
    forEach 方法用于对数组中的每个元素执行某种操作,但不返回任何值(返回 undefined)。
    const numbers = [1, 2, 3, 4]; numbers.forEach(num => console.log(num)); // 输出:1, 2, 3, 4
  3. some
    用途
    some 方法用于检查数组中是否至少有一个元素满足指定的条件。如果找到满足条件的元素,返回 true,否则返回 false。
    const numbers = [1, 2, 3, 4]; const hasEven = numbers.some(num => num % 2 === 0); // true
  4. find
    用途
    find 方法用于查找数组中第一个满足指定条件的元素,并返回该元素。如果没有找到满足条件的元素,返回 undefined。
    const numbers = [1, 2, 3, 4]; const firstEven = numbers.find(num => num % 2 === 0); // 2
    5.findIndex
    findIndex 方法用于查找数组中第一个满足指定条件的元素的索引。如果找到满足条件的元素,返回该元素的索引;如果没有找到满足条件的元素,返回 -1。
    const numbers = [1, 2, 3, 4, 5]; const index = numbers.findIndex(num => num > 3); // 返回 3 console.log(index); // 输出:3
    6.filter
    filter 返回一个新数组,包含所有满足条件的元素,如果没有任何一个元素满足条件,filter 返回一个空数组。而 findIndex 只返回第一个满足条件的元素的索引。
    const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); // 返回 [2, 4] const index = numbers.findIndex(num => num % 2 === 0); // 返回 1

posted on   练练练  阅读(3)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
点击右上角即可分享
微信分享提示