• 【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
  • 相关阅读:
    shell中使用echo命令改变输出显示样式
    Shell脚本报错unary operator expected
    shell运行报 too many arguments错误
    写shell,运行出错:syntax error near unexpected token `$’do ”
    shell 脚本执行,出现错误bad interpreter: No such file or directory
    Linux 基本命令学习笔记
    如何运行 O’Reilly 书 Python for Finance 的源代码
    IntelliJ 中配置 Anaconda
    Windows 10 中安装 Anaconda 3
    Windows 中安装的 Python 如何卸载
  • 原文地址:https://www.cnblogs.com/gtea/p/15820310.html
Copyright © 2020-2023  润新知