一个很low的问题,forEach怎么跳出循环?
- 2019 年 12 月 4 日
- 筆記
方法一: try catch
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const _ = require('lodash'); let outArr = []; try { arr.forEach(obj => { console.log(obj); if (obj < 3) { outArr.push(obj); } else { throw new Error('brack'); } }); } catch (err) { }
方法二:污染forEach
代码偷自https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/every
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; Array.prototype.forEach = function(fun /*, thisArg */) { 'use strict'; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisArg, t[i], i, t) === false) return false; } return true; }; let outArr = []; arr.forEach(obj => { console.log(obj); if (obj < 3) { outArr.push(obj); } else { return false; } });
方法三:用替代品
1:用lodash的_.forEach代替
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const _ = require('lodash'); let outArr = []; _.forEach(arr, (index, obj) => { console.log(obj); if (obj < 3) { outArr.push(obj); } else { return false; } });
2:用every代替
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let outArr = []; arr.every((obj) => { console.log(obj); if (obj < 3) { outArr.push(obj); } else { return false; } return true; });
3:用some代替
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let outArr = []; arr.some((obj) => { console.log(obj); if (obj < 3) { outArr.push(obj); } else { return true; } });
4:for代替
5:while代替
6:do while代替