我有以下功能:
function filterDesiredURLs(tweet) {
tweet.entities.urls.forEach((url) => {
desiredURLs.forEach((regexPattern) => {
if (regexPattern.test(url['expanded_url'])) {
console.log('hello, im returning');
return true;
}
})
})
}
我称之为:
console.log(filterDesiredURLs(tweet));
推文是定义的对象。我可以看到函数确实正在返回,因为我在控制台中看到输出hello, im returning
,但console.log(filterDesiredURLs(tweet));
打印undefined
。我希望这对于作为异步操作的回调传递的匿名函数,但这不是异步,因此返回应该有效。发生了什么?
答案 0 :(得分:1)
当您像这样调用return
时,您将从最近的函数返回(在这种情况下,匿名函数作为参数传递给您的内部forEach
)。
来自docs:
return语句结束函数执行并指定值 返回函数调用者。
要实现目标,您可以尝试:
function filterDesiredURLs(tweet) {
let found = false;
tweet.entities.urls.forEach((url) => {
desiredURLs.forEach((regexPattern) => {
if (regexPattern.test(url['expanded_url'])) {
console.log('hello, im returning');
found = true;
/* don't need return because forEach does not expects a function that returns something; and you can't break forEach */
}
})
})
return found;
}
答案 1 :(得分:1)
return
不跨越函数边界运行。它只从最里面的函数返回。要做你想做的事,你可能想要filter
或find
加上some
:
function filterDesiredURLs(tweet) {
// First, you were missing a return in the outer function
// Without a return here, *this* function will return `undefined`
return tweet.entities.urls.filter(url => {
// We are using `filter` to reduce the URL list to only
// URLs that pass our test - this inner function needs to return
// a boolean (true to include the URL, false to exclude it)
return desiredURLs.some(regexPattern => {
// Finally, we use `some` to see if any of the regex patterns match
// This method returns a boolean value. If the function passed to it ever
// returns true, it terminates the loop and returns true
// Otherwise, it iterates over the entire array and returns false.
return regexPattern.test(url['expanded_url']);
});
});
}
答案 2 :(得分:0)
javascript forEach
方法返回undefined
。
forEach
是一个将数组保留为不可变并返回一个新数组的操作。在您的代码中,forEach
方法被调用,并且它不返回任何内容,因此undefined
。