javascript 过滤函数 - 回调函数问题
javascript filter function - callback function issue
下面是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"]
每当你在回调中使用大括号时,你应该return一些东西
const result = words.filter((word) => {
return word.length > 6;
});
这对你有用
实际上,您需要 return 函数中的 Boolean
值,以便它进行相应的过滤
见-
const result = words.filter((word) => {
return word.length > 6;
});
下面是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"]
每当你在回调中使用大括号时,你应该return一些东西
const result = words.filter((word) => {
return word.length > 6;
});
这对你有用
实际上,您需要 return 函数中的 Boolean
值,以便它进行相应的过滤
见-
const result = words.filter((word) => {
return word.length > 6;
});