javascriptgogo-wasm

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


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>


Solution

  • 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.