javascript - 在纯现代 javascript 中调试数组方法链中间结果

标签 javascript ecmascript-6

我想在方法链的中间查看数组的状态:

arr.filter(...)
   .flatMap(...)
   .map(...)
   .sort()  // fyi, sort returns the sorted array
   // say I want to see the array content at this point
   .map(...)
   .slice(0, 10)

我可以通过在 underscorejs 中使用 tap() 函数来实现这一点,如 this answer 中所述。 .但是我想在不使用任何库的情况下执行此操作。

我浏览了Array prototype functions而且好像没有类似tap功能的功能。任何解决方法?

最佳答案

自己写一个:

// Be careful when overriding the default prototype, it might cause other code to fail or is a performance nightmare
Object.defineProperty(Array.prototype, "log", {
  enumerable: false, // < make sure it doesnt suddenly appear somewhere (defaults to false though)
  value(name) {
    console.log(name, this);
    return this; // < enable chaining
  },
});

[1, 2, 3].filter(it => it > 1).log("after filtering");

如果你想自动记录,你可以写一个可链接的包装器:

const logChain = (arr) => ({
  log() {
   console.log(arr);
   return this;
  },
  result() { return arr; },
  map(cb, context) { 
    return logChain(arr.map(cb, context)).log();
  },
  // filter reduce etc.
});

logChain([1, 2, 3])
  .map(it => it + 1) // logs [2, 3, 4]
  .result() // unwrap

或者,如果您想用最少的代码实现这一点,只需执行以下操作:

const log = (...mutations) => arr => mutations.reduce((prev, op) => (it => (console.log(it), it))(op(prev)), arr);

log(
 it => it.map(n => n + 1),
 it => it.filter(it => it > 2)
)([1, 2, 3, 4])

关于javascript - 在纯现代 javascript 中调试数组方法链中间结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55248000/

相关文章:

javascript - 如何使用node.jsexpress响应XML?

javascript - 无法在node.js中发出ajax请求

javascript - 刷新页面时确保保持在同一 div 区域

javascript - 在高阶函数中传递附加参数

javascript - 将 Angular 从 5.1 升级到 8 后 NgStyle 出现问题

javascript - 如何使用 nlapiLoadRecord 获取记录类型?

javascript - HTML5 Canvas - 轮子旋转功能行为异常

javascript - 使用JavaScript的Reduce从对象数组创建数组

javascript - 在深层嵌套对象中按特定键查找所有值

javascript - 访问 Javascript ES6 类中声明的函数(ES2015?ES16?)