英文:
How can I pass an array of string `string[]` from js to go using `syscall/js`
问题
有这样一个Go函数:
func WasmCount(this js.Value, args []js.Value) interface{} {
const firstParam = args[0].ArrayOfString() // <-- 我想要实现这个
return firstParam.Length
}
我将在JavaScript中这样调用它:
WasmCount(["a", "b"]) // 应该返回2
我可以传递String
和Int
,但找不到传递Array of <T>
的方法。
英文:
having this go function
func WasmCount(this js.Value, args []js.Value) interface {} {
const firstParam = args[0].ArrayOfString() // <-- I want to achieve this
return firstParam.Length
}
and I will call it from js like this
WasmCount(["a", "b"]) // it should return 2
I can pass String
and Int
but didn't find a way to pass an Array of <T>
答案1
得分: 2
这是Go代码从js.Value
中提取切片的责任。请参考下面的示例:
func WasmCount(this js.Value, args []js.Value) any {
if len(args) < 1 {
fmt.Println("参数数量无效")
return nil
}
arg := args[0]
if arg.Type() != js.TypeObject {
fmt.Println("第一个参数应该是一个数组")
return nil
}
firstParam := make([]string, arg.Length())
for i := 0; i < len(firstParam); i++ {
item := arg.Index(i)
if item.Type() != js.TypeString {
fmt.Printf("索引为%d的项应该是一个字符串\n", i)
return nil
}
firstParam[i] = item.String()
}
return len(firstParam)
}
这个示例修改自这个答案:https://stackoverflow.com/a/76082718/1369400。
英文:
It's the go code's responsibility to extract the slice from a js.Value
. See the demo below:
func WasmCount(this js.Value, args []js.Value) any {
if len(args) < 1 {
fmt.Println("invalid number of args")
return nil
}
arg := args[0]
if arg.Type() != js.TypeObject {
fmt.Println("the first argument should be an array")
return nil
}
firstParam := make([]string, arg.Length())
for i := 0; i < len(firstParam); i++ {
item := arg.Index(i)
if item.Type() != js.TypeString {
fmt.Printf("the item at index %d should be a string\n", i)
return nil
}
firstParam[i] = item.String()
}
return len(firstParam)
}
This demo is modified from this answer: https://stackoverflow.com/a/76082718/1369400.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论