简体   繁体   English

如何检查变量是否是C#中嵌入的Javascript(noesis.Javascript)中的数组?

[英]how to check if a variable is an Array in Javascript(noesis.Javascript) embedded in c#?

Anyone here have experience with Javascript.Net? 这里有人对Javascript.Net有经验吗?
I'm embedding javascript in c# using JavaScript.Net . 我正在使用JavaScript.Net将javascript嵌入c#中。
I have simple task to check if i given variable is a valid Array or not. 我有一个简单的任务来检查给定的变量是否为有效数组。 I have managed to get the correct answer by attaching the variable in script. 通过在脚本中附加变量,我设法获得了正确的答案。
This method works and returns true : 此方法有效并返回true

JavascriptContext context = new JavascriptContext();
public static string IsValidArray(string vari , JavascriptContext context)
        {

            object isValid = context.Run(@" 
                function check(){ var arr = " + vari + ";if(arr.constructor == Array){return true; }else {return false;}} check();");


            return (string)isValid;

        }

Its working fine. 它的工作正常。 But when I try to pass this variable as an argument of function, it returns false. 但是,当我尝试将此变量作为函数的参数传递时,它返回false。 Here's the code: 这是代码:

JavascriptContext context = new JavascriptContext();
string array = "['hello','hello2']";
           context.SetParameter("arr", array);
           string isValid = IsValidArray(context);

 public static string IsValidArray(JavascriptContext context)
        {        
            object isValid = context.Run("function check(vari){return (vari.constructor == Array);} check(arr);");
            return (string)isValid;          
        }

how to do it with arguments? 如何使用参数呢?

I'll elaborate on my comment. 我将详细说明我的评论。

I think your problem is that you are passing a string representation of an array, and not an array. 我认为您的问题是您正在传递数组的字符串表示形式,而不是数组。 You can try something like context.SetParameter("arr", new[] {"hello", "hello2")); 您可以尝试使用诸如context.SetParameter(“ arr”,new [] {“ hello”,“ hello2”)))之类的东西。

If you have a string, and want to convert it to an object, I would suggest using Json.NET, which is simply great. 如果您有字符串,并且想要将其转换为对象,我建议您使用Json.NET,这简直很棒。 Search for a tutorial on how to install it. 搜索有关如何安装它的教程。 Then you can simply do: 然后,您可以简单地执行以下操作:

string json = "['hello','hello2']";
List<String> array = Newtonsoft.Json.JsonConvert.DeserializeObject<List<String>>(json);

The alternative, but I don't know enough of JavaScript.Net to tell you what is preferable, is to read the string as is, then pass it into JavaScript, knowing it is just a string, and then calling JSON.parse(theString) in JavaScript in order to interpret it as an array, or object, or whatever. 另一种选择是,但我对JavaScript.Net知之甚少,不能告诉您什么是更可取的方法是按原样读取字符串,然后将其传递给JavaScript,知道它只是一个字符串,然后调用JSON.parse(theString) ,以便将其解释为数组,对象或其他内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM