1

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>

Zeke Lu
  • 6,349
  • 1
  • 17
  • 23
amd
  • 20,637
  • 6
  • 49
  • 67

1 Answers1

2

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.

Zeke Lu
  • 6,349
  • 1
  • 17
  • 23