javascript筛选函数-回调函数问题

enyaitl3  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(486)

此问题已在此处找到答案

何时应在es6箭头函数中使用返回语句(6个答案)
昨天关门了。
下面是带有过滤功能的javascript代码。当使用下面的代码时,它可以完美地工作-

  1. const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
  2. const result = words.filter(word => word.length > 6);
  3. console.log(result);
  4. // expected output: Array ["exuberant", "destruction", "present"]

但下面的代码给出了一个空数组。为什么?

  1. const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
  2. const result = words.filter((word) => {
  3. word.length > 6;
  4. });
  5. console.log(result);
  6. // expected output: Array ["exuberant", "destruction", "present"]
hjqgdpho

hjqgdpho1#

事实上,你需要归还 Boolean 函数中的值,以便进行相应的筛选
看-

  1. const result = words.filter((word) => {
  2. return word.length > 6;
  3. });
wfveoks0

wfveoks02#

无论何时在回调中使用花括号,都应该返回一些内容

  1. const result = words.filter((word) => {
  2. return word.length > 6;
  3. });

这对你有用

相关问题