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

  哎,菜是原罪!

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM