Blazor JS 互操作:如何将 undefined 传递给 JavaScript 函数

6
在 Blazor 项目中,JavaScript 函数区分 nullundefined。当从 C# 中传递 null (await jsRuntime.InvokeAsync<long>("func", null, "str")) 时,JS 侧接收到的值为 nulltypeof arg1 === 'object')。如何从 C# 侧传递参数以接收 undefinedtypeof arg1 === 'undefined')?
编辑: 显然,null 的行为不一致,这取决于参数的位置。 JS:
        func1: function (arg1) {
            console.log("func1", typeof arg1);
        },
        func2: function (arg1, arg2) {
            console.log("func2", typeof arg1);
        },

C#:

        await jsRuntime.InvokeVoidAsync("utils.func1", null);
        await jsRuntime.InvokeVoidAsync("utils.func1");
        await jsRuntime.InvokeVoidAsync("utils.func1", "aaa");
        await jsRuntime.InvokeVoidAsync("utils.func2", null, 123);
        await jsRuntime.InvokeVoidAsync("utils.func2", "aaa", 123);

输出:

func1 undefined
func1 undefined
func1 string
func2 object
func2 string

2
你尝试过使用 await jsRuntime.InvokeAsync<long>("func") 吗? - Eliseo
没有复现。你能发一下JS func()吗?并告诉我们你正在使用哪个版本。 - H H
编辑:添加了一个可以重现问题的示例。当然,在JS中可以省略末尾的参数以获取“undefined”。我的问题是如何在中间参数处获取未定义值。 - SergeyS
1个回答

1

如果你想知道在javascript函数中你是否发送了参数或者是null,你可以使用===undefined===null

<script>
    var func1=(arg1)=> {
        console.log("func1", arg1,arg1===null,arg1===undefined,typeof arg1);
    }
</script>

但你需要显式地发送“null”。
    var data = (string)null; //<--I check with this
    await JSRuntime.InvokeAsync<string>("func1","Hello world");
    await JSRuntime.InvokeAsync<string>("func1", data);
    await JSRuntime.InvokeAsync<string>("func1");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接