我想在方法链的中间查看数组的状态:
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/