【发布时间】: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