Jint Array functions ECMA 5.1

2019-05-27 01:05发布

问题:

I'm attempting to use Jint (v2.10.4.0) to translate one arbitrary JSON structure to another. However, I am having issues with using map.

According to the ECMA 5.1 language spec, map should exist on Array.prototye. However, when I attempt to use it, I get an error: Jint.Runtime.JavaScriptException: 'Object has no method 'map''

I'm testing this like

Engine engine = new Engine();
var doubles = engine.SetValue("x", "[ 1, 2, 3, 4, 5 ]")
    .Execute("x.map(function(a){ return a + a; })")
    .GetCompletionValue()
    .ToObject();
Console.WriteLine(doubles);
Console.ReadKey();

Ideally, I'd also like to use find, although this is ECMA6. Is there something I'm missing to use Array.Prototype.map or is there a way of introducing polyfills for Jint?

回答1:

Your code is adding a string value as x, so Jint can't find map on the string instance. You probably assumed that the SetValue method was evaluating the parameter as a script but it's actually just assigning a .NET object to a JavaScript varialble.

To assign an array you either need to pass a C# array like SetValue("x", new [] { 1, 2, 3, 4, 5 }) or run the equivalent script like Execute("var x = [1, 2, 3, 4, 5 ]").