在ES6中使用简写符号进行调试 - 过滤,映射,拒绝或减少

时间:2017-11-22 03:31:29

标签: javascript ecmascript-6 functional-programming

如何使用ES6简写将console.log放入过滤器,映射,缩小或拒绝?

words.filter(word => word.length > 6);

ES6版本



const words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

let longWords = words.filter(word => word.length > 6); //NEED AN EXAMPLE FOR HERE

// Filtered array longWords is ["exuberant", "destruction", "present"]

console.log(longWords);




可能在这里



const words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

let longWords = words.filter(function(word) {
  console.log(word);
  return word.length > 6;
});




3 个答案:

答案 0 :(得分:3)

您可以使用或者因为控制台不会返回任何内容

word => console.log(word) || word.length > 6

我个人只是使​​用括号和返回,如果我需要调试

答案 1 :(得分:1)

如果您正在寻找一个不会遮挡关键操作的可重复使用的代码段,您可以先定义帮助程序:

const firstDo = f => g => (...args) => (f(...args), g(...args));

这需要两个函数并返回一个新函数。新函数使用相同的参数调用fg,但返回 g(...args)的结果。

这样,您就可以点按mapreducefilterevery等,并在调试完成后轻松删除日志记录。

对于filter示例,调试记录器可以是:

const logLength = str => console.log(`Length of "${str}": ${str.length}`);

现在,您可以将谓词包装在:

const tapLog = firstDo(logLength);

const longWords = words.filter(tapLog(x => x > 6));

在一个工作示例中,包含reduce示例:

const words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

const firstDo = f => g => (...args) => (f(...args), g(...args));

const logLength = str => console.log(`Length of "${str}": ${str.length}`);



const firstLogLength = firstDo(logLength);

const pred = x => x.length > 6;

// in a filter
console.log(
  words.filter(firstLogLength(pred))
);

// In a reduce
const sum = (a, b) => a + b;
const logSumProg = firstDo((a, b) => console.log(`${a} + ${b}`));

console.log(
  [1,2,3,4,5].reduce(logSumProg(sum))
)

答案 2 :(得分:1)

根据您要调试的内容,可以更轻松地设置条件断点。

let longWords = words.filter(word => word.length > 6);

在Firefox调试器中,您可以右键单击要调试的代码行。然后选择"添加条件断点",例如添加typeof word !== 'undefined' && word == 'some word'。现在,当您运行代码时,如果满足这些条件,代码的执行将暂停,您可以使用常用的调试器函数。

您应该尽可能避免更改代码以进行调试。