1. 程式人生 > >js中forEach與for迴圈小結

js中forEach與for迴圈小結

最近在用forEach迴圈時,想查詢某個陣列id上個id的值,進行位置顛倒。思路是找到便利陣列id,找到相等的便跳出迴圈。結果發現return false只退出當前迴圈,並沒有跳出forEach迴圈。於是只能用for迴圈break做了處理。

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迴圈的方法

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)
    },

  哎,菜是原罪!