Javascript 从匿名函数返回,赢得';即使它';它不是异步的
我有以下功能:Javascript 从匿名函数返回,赢得';即使它';它不是异步的,javascript,asynchronous,return,anonymous-function,Javascript,Asynchronous,Return,Anonymous Function,我有以下功能: function filterDesiredURLs(tweet) { tweet.entities.urls.forEach((url) => { desiredURLs.forEach((regexPattern) => { if (regexPattern.test(url['expanded_url'])) { console.log('hello, im returning');
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));
其中tweet是一个已定义的对象。我可以看到函数确实在返回,因为我在控制台中看到输出
hello,im返回
,但是console.log(filterDesiredURLs(tweet))代码>打印未定义的
。对于作为异步操作回调传递的匿名函数,我希望这样做,但这不是异步的,因此返回应该可以工作。发生了什么?当您这样调用return
时,您是从最近的函数返回的(在本例中,匿名函数作为参数传递给内部forEach
)
从:
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;
}
当您这样调用return
时,您是从最近的函数返回的(在本例中,匿名函数作为参数传递给内部forEach
)
从:
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;
}
javascriptforEach
方法返回undefined
forEach
是一种将数组保留为不可变并返回新数组的操作。在代码中,调用了forEach
方法,它不返回任何内容,因此undefined
javascriptforEach
方法返回undefined
forEach
是一种将数组保留为不可变并返回新数组的操作。在代码中,调用了forEach
方法,它不返回任何内容,因此undefined
return
不会跨函数边界运行。它只从最里面的函数返回。要想做你想做的事情,你可能需要或需要:
return
不跨函数边界运行。它只从最里面的函数返回。要想做你想做的事情,你可能需要或需要:
你从内部函数返回,而不是外部函数Array#forEach
忽略其回调的返回值。看起来您的代码应该使用and而不是两个forEach
循环。您是从内部函数返回,而不是从外部函数返回Array#forEach
忽略其回调的返回值。看起来您的代码应该使用and而不是两个forEach
循环。return
不会破坏forEach的,
,它只会退出单个迭代。把它想象成一个继续循环中的语句。返回
不会破坏forEach的,
,它只会退出单个迭代。把它想象成一个继续在for
循环中的code>语句。注意,根据正则表达式的复杂度和数量,将所有正则表达式组合在一起并使用组合的正则表达式测试一次可能更有意义。但这可能是一种微观优化。请注意,根据正则表达式的复杂度和数量,将所有正则表达式组合在一起并使用组合的正则表达式测试一次可能更有意义。但这可能是一个微观优化。