如何编写从underscore.js仿真_.each()的函数

问题描述 投票:0回答:2

有一项练习,我不能把头缠起来。我需要编写一个模拟underscore.js函数_.each()的函数,该函数可以产生相同的结果并通过以下测试:

  • 应该遍历数组
  • 应该遍历一个对象
  • 应该忽略对象原型
  • 应访问原始收藏集
  • 如果通过则应绑定到上下文
  • 应返回收藏集

这是给定的空函数:

_.each= function (collection, iteratee, context) {} 

这是我到目前为止所写的,没有通过任何测试:

  _.each = function (collection, iteratee, context) {
    if (Array.isArray(collection)) {
      for (let key of collection) {
        console.log(key, collection.keys());
      }
    } else {
      for (let prop in collection) {
        if (collection.hasOwnProperty(prop)) {
          console.log(`${prop}: ${collection[prop]}`);
        }
      }
    }
    return collection
  };

我在这里要做的是使用for of循环遍历数组,并使用for in循环遍历对象,而忽略对象原型属性。我实际上不希望有问题的解决方案,也不想有特定的代码,只是希望朝着正确的方向前进,然后自己找到解决方案。我对JS很陌生,我承认我真的想不出解决此问题的方法。任何建议将不胜感激。谢谢

javascript underscore.js each
2个回答
0
投票

通常,对Each实现的测试始于创建示例函数和示例集合,然后在它们上调用函数。例如:

var array0 = [1,2,3];
var array1= [];
var iteratee = function (item) {
array1.push(item * 2);
}

当在每个项目上调用该函数时,它将执行已指定的操作。因此,在这种情况下,它将把每个项目乘以2的结果推入空数组。上面示例的预期输出将是其中包含[2,4,6]的array1。由于在调用iteratee时尚未编​​写部件,因此在运行测试时,什么都不会发生。


0
投票

这里是一个提示。我希望这能将您推向正确的方向。

_.each = function (collection, iteratee, context) {
  // you're going to want something that checks length of arguments and binds context here

  if (Array.isArray(collection)) {
    for (let key of collection) { /* you're gonna need the index later so consider using
                                     for (let i = 0; i < collection.length; i++) {...} */

      console.log(key, collection.keys()); // replace this line with calling iteratee with item, i, and collection
    }
  } else {
    for (let prop in collection) {
      if (collection.hasOwnProperty(prop)) {
        console.log(`${prop}: ${collection[prop]}`); // replace this line with calling iteratee with collection[prop], prop, and collection
      }
    }
  }
  return collection
};
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.