【发布时间】:2020-09-27 01:08:01
【问题描述】:
我想在我的 javascript 代码中像这段代码一样以动态方式使用函数。
const function1 = (param) => {
return "AA" + param
}
const function2 = (param) => {
return "BB" + param
}
const function3 = (param) => {
return "CC" + param
}
for (let i=1; i < 4; i++) {
// call function1, 2, 3 with i
}
我在python中也看到过类似这样的案例。
note1 = "note1"
note2 = "note2"
note3 = "note3"
for i in range(1, 4):
print(vars()[f"note{i}"])
像这个python案例,有没有办法用动态名称处理javascript变量或函数?
【问题讨论】:
-
使它们成为对象的属性,所以
myObj['1'] = param => {...}然后myObj[i]()。
标签: javascript python function variables ecmascript-6