- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-06-2024 06:52 AM
Hi All,
I have a script include with a forEach Loop. I'm trying to call another function inside it but it is not being called.
I replaced the Loop with a for loop and it did worked.
the for loop:
for(i=0; i<groups.length; i++){
allUsers = arrayUtil.concat(allUsers, this.myFunction(tableName, 'group' = groups[i], variable));
}
the foreach loop:
groups.forEach(function(group){
allUsers = arrayUtil.concat(allUsers, this.myFunction(tableName, 'group' = group, variable));
}
Does anyone have an idea why is this happening?
Thanks in advance 🙂
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-06-2024 07:56 AM
Hi @Snow Tomcal
when using iterative array methods (e.g., forEach, map, filter), the this value inside the callback is usually undefined.
https://www.w3schools.com/js/js_this.asp
can you try this instead.
assign the function definition to a variable outside the forEach loop and pass it as the second parameter to the forEach
var myFunc = this.myFunction
groups.forEach(function(group){
allUsers = arrayUtil.concat(allUsers, myFunc(tableName, 'group' = group, variable));
},myFunc);
Regards,
Chaitanya
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-06-2024 07:56 AM
Hi @Snow Tomcal
when using iterative array methods (e.g., forEach, map, filter), the this value inside the callback is usually undefined.
https://www.w3schools.com/js/js_this.asp
can you try this instead.
assign the function definition to a variable outside the forEach loop and pass it as the second parameter to the forEach
var myFunc = this.myFunction
groups.forEach(function(group){
allUsers = arrayUtil.concat(allUsers, myFunc(tableName, 'group' = group, variable));
},myFunc);
Regards,
Chaitanya
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-06-2024 11:03 PM
It worked!
Thanks:))
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-06-2024 10:01 PM
Hi @Snow Tomcal
Hope this answere is useful to your question,
To resolve this Use an Arrow Function
Arrow functions do not have their own this context; they inherit it from the enclosing scope. You can replace your forEach loop with an arrow function like this
Javascript code
groups.forEach((group) => {
allUsers = arrayUtil.concat(allUsers, this.myFunction(tableName, 'group' = group, variable));
});
Regards,
Mule Syam Prasanna