[英]How to get the value of an anonymous function?
在我的 index.js 文件中,我調用 function iterateWagons
src/index.js
import { locomotive } from './data/train.js'
import { iterateWagons, filterOldBreaks } from './utils/train.js'
iterateWagons(
locomotive,
wagon => console.log(`🚂 ${wagon.name} is a locomotive`),
wagon => wagon.isLocomotive,
)
我的目標是實現這個 function...
當給定一個起點(機車)時,“步行”穿過整個火車。 共有三個參數:
src/utils/train.js
export const iterateWagons = (start, actionFn, filterFn) => { ... }
當我用console.log(filterFn)
打印出filterFn
時,控制台會打印出[Function (anonymous)]
並且我不知道這是對還是錯。
我怎樣才能訪問這個?
這是我的實施草案:
src/utils/train.js
export const iterateWagons = (start, actionFn, filterFn) => {
while (start.next) {
if (filterFn(start)) {
actionFn(start)
}
start = start.next
}
}
有了這個我得到錯誤TypeError: filterFn is not a function
我也試過只使用
if (filterFn)
但在這里我沒有得到false
true
更多信息:
console.log(filterFn)
-> [Function (anonymous)]
console.log(filterFn(start))
-> TypeError: filterFn is not a function
項目結構:
數據:
src/data/train.js
[...]
const wagon1 = {
name: 'W-10582',
emoji: '🚋',
lastBreakRevision: '2021-02-15',
next: wagon2,
}
export const locomotive = {
name: 'L-283',
emoji: '🚂',
isLocomotive: true,
next: wagon1,
}
小測試:
func = function(start, fn){fn(start)};
func(2, a=>console.log(`Test ${a}`));
這將在控制台上打印Test 2
。 因此,您的問題可能出在您沒有展示的實現中。
我認為的問題是您不了解 scope。 當您傳遞參數時,您正在調用 function 然后它運行,然后它就完成了。 您確實可以在外部 function 的 scope 內傳遞您傳遞的回調 function 的 console.log() 值。
function t(fooFn) { console.log('Foo is ' + fooFn()) } t(() => 'value of foo')
如您所見,當您傳遞箭頭 function 時,您可以調用它並從中獲取一個值並 console.log 它,就像我在本示例中所做的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.