我在代码中以两种方式调用对象方法:
this.reveal.updateVisuals(i, 'show')
;
或
this.reveal.updateVisuals(i, 'hide');
我将隐藏和显示条件作为字符串传递,以便稍后进行评估并用作方法。请注意条件:if (effect === 'show/hide')。
updateVisuals: function (time, effect) {
// Check if parameter exists and property can be read
if (this.breakpointsMap && typeof this.breakpointsMap[checkTime] !== "undefined") {
if (effect === 'show') {
// display the items that were fast forwarded
var k = this.breakpointsMap[checkTime].length;
while (k--) {
try {
this.breakpointsMap[checkTime][k].show();
} catch (err) {}
}
} else if (effect === 'hide') {
// display the items that were fast forwarded
var k = this.breakpointsMap[checkTime].length;
while (k--) {
try {
this.breakpointsMap[checkTime][k].hide();
} catch (err) {}
}
}
}
}
但是代码似乎是重复的,我想知道是否有一种方法可以将 hide 或 show 作为方法传递给该方法,并在需要时将其应用到数组上。我尝试过这样的事情:
this.reveal.updateVisuals(i).show
最佳答案
您可以使用多种方法来简化此操作,以下是其中几种:
updateVisuals: function (time, effect) {
if (this.breakpointsMap && typeof this.breakpointsMap[checkTime] !== "undefined") {
this.breakpointsMap[checkTime].forEach(e => e[effect]());
}
}
或者返回数组:
updateVisuals: function (time, effect) {
if (this.breakpointsMap && typeof this.breakpointsMap[checkTime] !== "undefined") {
return this.breakpointsMap[checkTime];
}else{
return [];
}
}
this.reveal.updateVisuals(i).forEach(e => e.show());
关于javascript - 将方法 hide/show 传递给另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46564965/