js中Array.forEach跳出循环的方法实例

作者:陌生的L君 时间:2024-05-11 09:32:22 

目录
  • forEach()方法

  • js中 Array.forEach如何跳出循环

    • 解决方式:

  • 总结

    forEach()方法

    语法:array.forEach(callback(currentvalue,index,arr) ,thisValue)

    其中

    callback为数组中每个元素执行的函数,该函数可接受1-3个参数:

    • currentvalue参数表示数组的当前元素项,必须的参数

    • index参数表示的当前元素下标,可选参数

    • arr参数表示当前元素所属的数组,可选参数

    thisValue表示执行回调函数callback()时的this指向。可选参数。当不写时,则默认是指向window全局

    示例


       var arr = [1, 3, 5, 13, 2];
       var res = arr.forEach(function(item,index) {
           console.log(`数组第${index+1}个元素是${item}`);
       })
       console.log(res);//forEach的返回值为undefined,

    运行结果:

    js中Array.forEach跳出循环的方法实例

    js中 Array.forEach如何跳出循环

    forEach是不能通过break或者return跳出循环的,一般跳出循环的方式为抛出异常:


    try {
      let array = [1, 2, 3, 4]
      array.forEach((item, index) => {
        if (item === 3) {
          throw new Error('end')//报错,就跳出循环
        } else {
          console.log(item)
        }
      })
    } catch (e) {
    }

    这种写法反而很麻烦。

    解决方式:

    1.使用every替代:


    let array = [1, 2, 3, 4]
    array.every((item, index) => {
     if (item === 3) {
       return true
     } else {
       console.log(item)
     }
    })

    2.自己写一个😁


    //可跳出循环的数组遍历
    Array.prototype.loop = function(cbk) {
     //判断当前数组是否为空
     if (this?.length) {
       for (let i = 0; i < this.length; i++) {
         let stop = cbk(this[i], i, this)
         //判断是否停止循环
         if (stop) {
           break
         }
       }
     }
    }

    let array = [1, 2, 3, 4]
    array.loop ((item, index) => {
     if (item === 3) {
       return true
     } else {
       console.log(item)
     }
    })

    来源:https://blog.csdn.net/qq_34157798/article/details/120016609

    标签:array.foreach,跳出,循环
    0
    投稿

    猜你喜欢

  • Python Pandas数据中对时间的操作

    2023-06-10 00:50:57
  • Python利用pyHook实现监听用户鼠标与键盘事件

    2021-09-04 19:59:59
  • MySQL怎么给字符串字段加索引

    2024-01-25 10:19:57
  • 利用Pandas索引和选取数据方法详解

    2023-04-30 23:30:07
  • java数据库开发之JDBC基础使用方法及实例详解

    2024-01-21 04:37:00
  • 浅析Oracle中sys、system和Scott用户下的数据库连接问题

    2023-07-02 15:14:06
  • Python第三方库qrcode或MyQr生成博客地址二维码

    2023-06-25 06:23:08
  • 解决vue项目中某一页面不想引用公共组件app.vue的问题

    2023-07-02 16:57:35
  • 如何利用Python获取鼠标的实时位置

    2022-08-11 07:00:33
  • Python requests用法和django后台处理详解

    2023-06-12 02:05:42
  • PHP微信支付实例解析

    2024-05-02 17:15:56
  • python单例模式的多种实现方法

    2023-05-01 12:05:04
  • Python numpy之线性代数与随机漫步

    2021-12-04 05:20:01
  • 一个简单的MySQL备份Shell脚本

    2024-01-22 16:44:24
  • C#使用checkedListBox1控件链接数据库的方法示例

    2024-01-24 19:15:09
  • 从trim原型函数看js正则表达式的性能

    2008-12-11 13:55:00
  • MySQL DQL语句的具体使用

    2024-01-21 08:17:03
  • 基于Go和PHP语言实现爬楼梯算法的思路详解

    2024-05-22 10:18:20
  • python数组和矩阵的用法解读

    2023-07-13 07:38:18
  • Pytorch实现将label变成one hot编码的两种方式

    2021-08-26 08:45:00
  • asp之家 网络编程 m.aspxhome.com