zoukankan      html  css  js  c++  java
  • 【JS学习】js中forEach与for循环

    最近在用forEach循环时,想查找某个数组id上个id的值,进行位置颠倒。思路是找到便利数组id,找到相等的便跳出循环。结果发现return false只退出当前循环,并没有跳出forEach循环。于是只能用for循环break做了处理。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    upSort () {
          var upId = -1
          // this.tableData.forEach(item => {
          //   if (item.id === this.checkId) {
          //     return false // 结束不了forEach循环 只是结束本次循环体
          //   }
          //   upId = item.id
          // })
          for (let i=0;i<this.tableData.length;i++) {
            if (this.tableData[i].id === this.checkId) {
              break
            }
            upId = this.tableData[i].id
            console.log('upId ===',upId)
          }
          let params = [
            {id: this.checkId, sort: this.sort-1},
            {id: upId , sort: this.sort}
          ]
          console.log('params===',params)
        }

      后来网上看到一种利用异常处理跳出forEach循环的方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    upSort () {
          var upId = -1
          try {
            this.tableData.forEach(item => {
              if (item.id === this.checkId) {
                throw new Error('return false')
              }
              upId = item.id
            })
          } catch (e) {
            console.log(e)
          }
           
          let params = [
            {id: this.checkId, sort: this.sort-1},
            {id: upId , sort: this.sort}
          ]
          console.log('params===',params)
        },

      哎,菜是原罪!

    作者:gtea 博客地址:https://www.cnblogs.com/gtea
  • 相关阅读:
    Delphi中WebBrowser控件打开部分网站报"Invalid floating point operation”解决
    delphi中URL的汉字编码
    python手记(11)
    李维对VCL理解的几个错误
    如何配置MYSQL的MASTER---SLAVE复制备份?
    UniDAC连接Embedded MySQL server
    unigui组件中client javascript delphi组件之间的操作
    Delphi中SendMessage使用说明(所有消息说明) good
    iOS面试题
    Windows的MAX_PATH
  • 原文地址:https://www.cnblogs.com/gtea/p/15820310.html
Copyright © 2011-2022 走看看