简体   繁体   English

为什么只从Silverlight传递Javascript数组中的第一个元素?

[英]Why do I only get first element in Javascript array passed from Silverlight?

I'm attempting to pass out an array of strings from a Silverlight application to a Javascript function. 我正在尝试将一个字符串数组从Silverlight应用程序传递给Javascript函数。 However I only seem to get the first element of the array, rather than the whole array. 但是我似乎只得到数组的第一个元素,而不是整个数组。 I've reproduced it with the simple code below: 我用下面的简单代码复制了它:

Silverlight: Silverlight的:

 string[] Names = new string[5];
 Names[0] = "Test1";
 Names[1] = "Test2";
 Names[2] = "Test3";
 Names[3] = "Test4";
 Names[4] = "Test5";

 HtmlPage.Window.Invoke("PopulateNames", Names);

Javascript: 使用Javascript:

function PopulateNames(names)
{
    window.alert(names);
}

In this case I only ever see "Test1" with the above code, or "undefined" if I replace window.alert(names) with window.alert(names[0]). 在这种情况下,我只会在上面的代码中看到“ Test1”,如果将window.alert(names)替换为window.alert(names [0]),则只会看到“ undefined”。

Does anyone know how I should be doing this to get all the elements out to the Javascript function? 有谁知道我应该怎么做才能将所有元素都发送给Javascript函数?

The Invoke method takes an array of parameters. Invoke方法采用参数数组。
Therefore, your five strings are being passed as five string parameters to the function. 因此,您的五个字符串将作为五个字符串参数传递给该函数。

You need to pass a nested array, like this: 您需要传递一个嵌套数组,如下所示:

HtmlPage.Window.Invoke("PopulateNames", new object[] { Names });

There is another property of a javascript function object. javascript函数对象的另一个属性。 Its arguments. 它的论点。 You can access the complete object array you pass through this arguments object. 您可以访问通过此参数对象传递的完整对象数组。 Try debugging your script and you will understand what I say. 尝试调试您的脚本,您会明白我的意思。 If you access the argument array of the function like ' funcation(myargs[]) ', the myargs will refer to the first value in the passed in array. 如果您访问函数的参数数组,例如' funcation(myargs[]) ',则myargs将引用传入数组中的第一个值。

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

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