我在 init 函数中有一个循环:
fruits = {
apple: { color: 'green' },
banana: { color: 'yellow' },
kiwi: { color: 'green' }
}
ngOnInit() {
for ( let fruit in this.fruits ) {
if ( this.fruits[fruit].color === 'green' ) {
// I want to use the current iterator
this[fruit]()
}
}
}
如您所见,我正在尝试对满足条件的函数进行方法调用。这些函数将与“循环迭代器”同名——我只是不知道如何使用动态名称进行调用。
apple() { ... }
banana() { ... }
kiwi() { ... }
所以,如果你看一下循环中的条件,apple()
并且kiwi()
应该被调用,假设它们是绿色水果。
问题:如何在 ngOnInit 函数中正确组合函数调用?
我试过:this[fruit]()
, this.fruit()
, this['fruit']
. 什么是正确的方法?
我认为这将是做你想做的事情的正确方法
const fruits = {
apple: { color: 'green' },
banana: { color: 'yellow' },
kiwi: { color: 'green' }
}
ngOnInit() {
for ( let fruit in this.fruittree ) {
if ( fruits[fruit].color === 'green' ) {
// I want to use the current iterator
this[fruit]();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句