Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: for/in loop in JScript standards mode

0
0
Hi frolovm,

You're absolutely right. The for..in statement is broken for host objects in Standards Mode. Unfortunately this appears to be a JScript bug and therefore isn't likely to be fixed.

Consider however that for..in support is really only useful for IPropertyBag instances. All other host objects include instance methods, extension methods, and other undesirable members in the enumeration. This is by design, as some script engines (including JScript) don't have enumeration options for host object members.

There are several ways to enumerate host object members that work in Standards Mode and don't have the problem mentioned above. JScript's Enumerator class is one possibility:
engine.Execute(@"
    for (var e = new Enumerator(expandoObj); !e.atEnd(); e.moveNext()) {
        var item = e.item();
        Console.WriteLine('{0} = {1}', item.Key, item.Value);
    }
");
Unfortunately this currently doesn't work with IPropertyBag; that's a ClearScript bug that we'll fix in the next point release.

Another possibility might be to expose a JavaScript-friendly way to use .NET enumeration:
publicstaticclass IEnumerableExtensions {
    publicstaticvoid @foreach(this IEnumerable source, dynamic callback) {
        foreach (var item in source) {
            callback(item);
        }
    }
}
and then:
engine.AddHostType(typeof(IEnumerableExtensions));
engine.Execute(@"
    expandoObj.foreach(function(item) {
        Console.WriteLine('{0} = {1}', item.Key, item.Value);
    });
");
Finally, for scriptable name-value collections, you can always use native JavaScript objects instead of host objects:
dynamic someObj = engine.Evaluate("({})");
someObj.foo = 123;
someObj.bar = 456;
engine.Script.someObj = someObj;
Thanks for reporting this issue, and good luck!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images