javascript - 创建要在多个方法中多次调用的函数
问题描述
大家好,新年快乐!我需要一个我用多种方法重复多次的程序,拜托。我会给你写一个简短的例子:
method1() {
//I DO THINGS
const controlArray = [];
this.daySelected.forEach((element) => {
const tStart = element.time.map((t) => t.startIsGreater);
if (tStart.includes(true)) {
controlArray.push(tStart);
this.setNewEventInfoRequired(false);
this.setAlertWarning(true);
}
});
},
method2() {
//I DO OTHER THINGS DIFFERENT FROM THE FIRST METHOD
const controlArray = [];
this.daySelected.forEach((element) => {
const tStart = element.time.map((t) => t.startIsGreater);
if (tStart.includes(true)) {
controlArray.push(tStart);
this.setNewEventInfoRequired(false);
this.setAlertWarning(true);
}
});
},
// and then I repeat the same with other methods (methodFoo, methodBar, etc...)
我从 const controlArray 写到最后的所有内容,我在多个方法中重复相同的内容,那么如何将所有那段代码放在一个函数中并在方法中调用该函数?
解决方案
只需将通用代码放在一个方法中,然后在每个方法中调用它:
runCommonFunc(){ // give it a significative name
const controlArray = [];
this.daySelected.forEach((element) => {
const tStart = element.time.map((t) => t.startIsGreater);
if (tStart.includes(true)) {
controlArray.push(tStart);
this.setNewEventInfoRequired(false);
this.setAlertWarning(true);
}
});
},
method1(){
//I do things
this.runCommonFunc()
},
method21(){
//I do things
this.runCommonFunc()
}
推荐阅读
- python - 将列向量连接到矩阵的末尾
- latex - 使用 tcolorbox 在 \rule 行中的间隙
- list - 如何从列表列表中的两个索引创建一个元组?
- javascript - 全局变量不改变函数中的值
- mysql - 刚开始配置时无法连接到任何指定的MySQL主机
- powershell - Get-FileHash 无法读取文件
- c - 使用动态函数复制字符串
- java - 如何将 Hibernate 的 Session 注入 micronaut 中的异步侦听器?
- flutter - RangeError(索引):无效值:有效值范围为空:34
- javascript - 在 D3.js v5 中更改选定对象的属性