【问题标题】:javascript filter function - callback function issue [duplicate]javascript过滤器函数-回调函数问题[重复]
【发布时间】:2021-07-11 07:23:10
【问题描述】:

下面是带有过滤功能的javascript代码。使用下面的代码时,它可以完美运行-

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

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

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

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

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

const result = words.filter((word) => {
word.length > 6;
});

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

【问题讨论】:

  • 在第一种情况下,您没有使用花括号,因此它返回 word.length > 6 表达式输出。但在第二种情况下,您使用了花括号,因此您必须使用 return 关键字显式返回 true/false
  • 所以对于第二种情况,如果您执行(word) => { return word.length > 6;} 之类的操作,那么它将起作用。

标签: javascript arrays string filter callback


【解决方案1】:

实际上,您需要在函数中返回Boolean 值,以便它进行相应的过滤

看-

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

【讨论】:

    【解决方案2】:

    当你在回调中使用大括号时,你应该返回一些东西

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

    这对你有用

    【讨论】:

    • 不敢相信我的回答慢了 10 秒但是一样!
    • @Sanmeet hehe,我能感觉到你兄弟!!
    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2020-05-17
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多