jquery的each方法实现(带循环终止功能)
~function () {
function each(callback) {
if (!callback) return;
for (let i = 0; i < this.length; i++) {
let flag = callback(this[i], i);
if (flag === false) break;
}
}
function each1(arr, callback) {
if (!Array.isArray(arr) || !callback) return;
for (let i = 0; i < arr.length; i++) {
let flag = callback.call(arr, arr[i], i);
if (flag === false) break;
}
}
['each', 'each1'].forEach(item => {
Array.prototype[item] = eval(item);
})
}();
[1, 2, 3, 4].each((item, index) => {
console.log(item);
if (index >= 1) return false;
})
Array.prototype.each1([5,6,7],(item, index) => {
console.log(item);
if (index >= 1) return false;
})
网友评论