最近在用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)
},
哎,菜是原罪!
