什么是lodash
Lodash 是一个 JavaScript 实用工具库,提供了很多用于处理数据、简化开发等方面的功能。它提供了一组常用的工具函数,用于处理数组、对象、字符串等常见数据结构,同时也包含了一些函数式编程的工具。对于前端开发来说,是个很好用的工具,甚至看过有人说面试不会lodash被嘲讽了。
我所在的公司项目中也用了这个库,今天就听同事吐槽,他循环两万条数据,进入卡住了溢出了,找了半天问题,最后没想到是foreach的过,换成for循环就没问题了。
那么为什么呢,lodash是怎么实现foreach的呢?源码如下:
import arrayEach from './.internal/arrayEach.js';
import baseEach from './.internal/baseEach.js';
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `forIn`
* or `forOwn` for object iteration.
*
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see forEachRight, forIn, forInRight, forOwn, forOwnRight
* @example
*
* forEach([1, 2], value => console.log(value))
* // => Logs `1` then `2`.
*
* forEach({ 'a': 1, 'b': 2 }, (value, key) => console.log(key))
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach

本文分析了Lodash的forEach函数实现,包括其对数组和通用集合的处理,以及为何在大数据量下可能导致栈溢出。作者指出,对于大数据,应考虑使用非递归方法避免性能问题。
最低0.47元/天 解锁文章
4003

被折叠的 条评论
为什么被折叠?



