在 Blazor 项目中,JavaScript 函数区分 null
和 undefined
.当通过null
从 C# ( await jsRuntime.InvokeAsync<long>("func", null, "str")
) JS 端接收值 null
(typeof arg1 === 'object'
)。从 C# 端传递什么来接收 undefined
(typeof 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
最佳答案
如果您想知道您是否发送参数或javascript函数中是否为null,您可以使用===undefined
或 ===null
.
<script>
var func1=(arg1)=> {
console.log("func1", arg1,arg1===null,arg1===undefined,typeof arg1);
}
</script>
但你需要发送“空明确” 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");
关于javascript - Blazor JS 互操作 : how to pass undefined to a JavaScript function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64086277/