I have registered some javascript functions in the global scope:
function Test1() {}
function Test2() {}
Now I want to run all javascript functions whose name starts with 'Test', how to do it?
I want to prevent saving each functions into a variable because it does not scale. Nor to push them to a queue and execute them later, since people need to remember adding their functions to the queue when they write the test and I don't want that.
var globalKeys = Object.keys(window); for(var i = 0; i < globalKeys.length; i++){ var globalKey = globalKeys[i]; if(globalKey.includes("Test") && typeof window[globalKey] == "function"){ window[globalKey](); } }
function Test() { console.log('test') }
Object.keys(window).filter(s => s.startsWith('Test')) // [ "Test" ]
As you can see, functions are defined on the global scope.
const isTest = s => typeof s === 'function' && s.startsWith('Test')
Object.keys(window).filter(isTest).map(t => t())
I don't know your use case entirely, but I suspect it would be better to provide your own object.
const tests = {}
tests.Test1 = () => {/*...*/}
You could get all elements of window
and check them. Here is a basic starting point :
for(let objectName in window){ console.log(`${objectName} : ${typeof window[objectName]}`) }
Now objectName
is actually a string, it could be anything, just check if it starts with Test
, and if its type is a function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.