Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript ForEach Index Value! #58

Closed
egooner opened this issue Jun 27, 2018 · 2 comments
Closed

JavaScript ForEach Index Value! #58

egooner opened this issue Jun 27, 2018 · 2 comments
Assignees
Labels

Comments

@egooner
Copy link

egooner commented Jun 27, 2018

I have a JavaScript forEach iterating over a Host Object which has a simple IEnumerable Implemented

    public IEnumerator<T> GetEnumerator()
    {
        foreach (String cfgKey in configbag.KeyList)
        {
            T t = (T)configbag[cfgKey];
            if (t == null)
            {
                yield return default(T);
            }
            else
            {
                yield return t;
            }
        }
    }

The JavaScript works fine if I issue a simple

bags.forEach((bag) =>{do something with bag})

But if I want the Index too

bags.forEach((bag,n) =>{do something with bag but use n also})

n is Undefined.

Not sure what I need to add or if this is even possible? Can you advise what I need to do in order to obtain the index of the enumerated item. Obviously I could roll this back to a simple for loop or add my own index but I am trying to make the code work in the same way as a Javascript array object.

@egooner
Copy link
Author

egooner commented Jun 27, 2018

Oops too much code thought forEach was implemented in V8 but it seems to be my own extension!!!

@egooner egooner closed this as completed Jun 27, 2018
@egooner
Copy link
Author

egooner commented Jun 27, 2018

For anyone interested this is what the new forEach Extension I created looks like

public static class ScriptEnumerable
{
    public static void forEach<T>(this IEnumerable<T> source, object action)
    {
        int i = 0;        
        foreach (var item in source)
        {            
            ((dynamic)action)(item,i++,source);                       
        }        
    }
}

The original that I think I got from this forum when on CodePlex was

public static class ScriptEnumerable
{
    public static void forEach<T>(this IEnumerable<T> source, object action)
    {
        source.ToList().ForEach(item => ((dynamic)action)(item));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants