最近在用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) ???},
哎,菜是原罪!
js中forEach与for循环小结
原文地址:https://www.cnblogs.com/shichangchun/p/10118910.html