How can I pass an array of string `string[]` from js to go using `syscall/js`

huangapple go评论108阅读模式
英文:

How can I pass an array of string `string[]` from js to go using `syscall/js`

问题

有这样一个Go函数:

  1. func WasmCount(this js.Value, args []js.Value) interface{} {
  2. const firstParam = args[0].ArrayOfString() // <-- 我想要实现这个
  3. return firstParam.Length
  4. }

我将在JavaScript中这样调用它:

  1. WasmCount(["a", "b"]) // 应该返回2

我可以传递StringInt,但找不到传递Array of <T>的方法。

英文:

having this go function

  1. func WasmCount(this js.Value, args []js.Value) interface {} {
  2. const firstParam = args[0].ArrayOfString() // <-- I want to achieve this
  3. return firstParam.Length
  4. }

and I will call it from js like this

  1. 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中提取切片的责任。请参考下面的示例:

  1. func WasmCount(this js.Value, args []js.Value) any {
  2. if len(args) < 1 {
  3. fmt.Println("参数数量无效")
  4. return nil
  5. }
  6. arg := args[0]
  7. if arg.Type() != js.TypeObject {
  8. fmt.Println("第一个参数应该是一个数组")
  9. return nil
  10. }
  11. firstParam := make([]string, arg.Length())
  12. for i := 0; i < len(firstParam); i++ {
  13. item := arg.Index(i)
  14. if item.Type() != js.TypeString {
  15. fmt.Printf("索引为%d的项应该是一个字符串\n", i)
  16. return nil
  17. }
  18. firstParam[i] = item.String()
  19. }
  20. return len(firstParam)
  21. }

这个示例修改自这个答案: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:

  1. func WasmCount(this js.Value, args []js.Value) any {
  2. if len(args) &lt; 1 {
  3. fmt.Println(&quot;invalid number of args&quot;)
  4. return nil
  5. }
  6. arg := args[0]
  7. if arg.Type() != js.TypeObject {
  8. fmt.Println(&quot;the first argument should be an array&quot;)
  9. return nil
  10. }
  11. firstParam := make([]string, arg.Length())
  12. for i := 0; i &lt; len(firstParam); i++ {
  13. item := arg.Index(i)
  14. if item.Type() != js.TypeString {
  15. fmt.Printf(&quot;the item at index %d should be a string\n&quot;, i)
  16. return nil
  17. }
  18. firstParam[i] = item.String()
  19. }
  20. return len(firstParam)
  21. }

This demo is modified from this answer: https://stackoverflow.com/a/76082718/1369400.

huangapple
  • 本文由 发表于 2023年7月8日 20:38:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76642999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定