【发布时间】:2020-06-30 22:29:22
【问题描述】:
我写了这个函数,它基本上模拟了同名的 Underscore.js 函数。一切正常,除了我正在努力理解如何绑定到上下文,如果一个通过。我确定我应该使用 function.prototype.bind(),但我不确定如何实现它。
// _.each(collection, iteratee, [context])
// Iterates over a collection of elements (i.e. array or object),
// yielding each in turn to an iteratee function, that is called with three arguments:
// (element, index|key, collection), and bound to the context if one is passed.
// Returns the collection for chaining.
_.each = function (collection, iteratee, context) {
if(Array.isArray(collection)){
for(let i = 0; i < collection.length; i++){
iteratee(collection[i], i, collection);
};
};
if(typeof collection === 'object' && !Array.isArray(collection)){
Object.entries(collection).map(([key, value]) => {
iteratee(value, key, collection);
});
};
return collection;
};
【问题讨论】:
标签: javascript arrays function iteration bind