首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调试数组方法在纯现代javascript中链中间结果

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

Stack Overflow用户
提问于 2019-03-20 02:42:38
回答 1查看 281关注 0票数 1

我希望在方法链的中间看到数组的状态:

代码语言:javascript
复制
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函数的功能。有什么解决方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-20 02:50:44

只需自己编写一个:

代码语言:javascript
复制
// 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");

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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])
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55248000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档