Clearscript: How to consume the result such as V8Array?

Created on 26 Apr 2020  路  2Comments  路  Source: microsoft/ClearScript

Hi all,

I am new to ClearScript and just want to use it to execute some Javascirpts. The sample code is

var engine = new V8ScriptEngine();
var arrayRet = engine.Evaluate("var a = []; a.push('test');a;");

And my question is, how to convert arrayRet to the Array or List in C# ?

I checked the type of arrayRet and it's type is V8ScriptItem.V8Array, but it seems that I cannot use this class directly.

In conclusion, I want to use the result of Evaluate... how to do that ?

Thanks~~

question

All 2 comments

Hi @xingtanzjr,

Generally you can access script objects via dynamic:

``` C#
dynamic arrayRet = engine.Evaluate("var a = []; a.push('test'); a;");
var length = (int)arrayRet.length;
for (var index = 0; index < length; ++index) {
Console.WriteLine(arrayRet[index]);
}


Another possibility is to use [`ScriptObject`:](https://microsoft.github.io/ClearScript/Reference/html/T_Microsoft_ClearScript_ScriptObject.htm)

``` C#
var arrayRet = (ScriptObject)engine.Evaluate("var a = []; a.push('test'); a;");
var length = (int)arrayRet["length"];
for (var index = 0; index < length; ++index)  {
    Console.WriteLine(arrayRet[index]);
}

Additionally V8 arrays implement IList, so you can also do something like this:

C# var arrayRet = (IList)engine.Evaluate("var a = []; a.push('test'); a;"); foreach (var item in arrayRet) { Console.WriteLine(item); }

Good luck!

@ClearScriptLib Thanks锛乀hat's exactly what I need

Was this page helpful?
0 / 5 - 0 ratings