js函数调用的go函数中不能return一个数组。恐慌:ValueOf:无效值

Cannot return an array in go function that is invoked by js function. panic: ValueOf: invalid value

有个gocode,编译成wasm文件。我想要 return 数组的函数之一,但是当我这样做时,我看到 panic: ValueOf: invalid value 错误。 js.ValueOf 函数似乎可以处理一个数组:

...
case []interface{}:
    a := arrayConstructor.New(len(x))
    for i, s := range x {
        a.SetIndex(i, s)
    }
    return a
...

但当我给它一个 []int 值时仍然会出现恐慌。

package main

import (
    "fmt"
    "syscall/js"
)

var signal = make(chan int)

func keepAlive() {
    for {
        <-signal
    }
}

func main() {
    js.Global().Set("PanicStation", js.FuncOf(PanicStation))
    keepAlive()
}

func PanicStation(this js.Value, args []js.Value) interface{} {
    arr := make([]int, 1)
    return arr
}

使用[]interface{}

[]int[]interface{} 不同。如果 []interface{} 适合您,请创建并 return:

arr := make([]interface{}, 1)

例如,如果您 return 这个切片:

func PanicStation(this js.Value, args []js.Value) interface{} {
    return []interface{}{1, "two"}
}

运行 PanicStation() 在 JavaScript 控制台会输出:

> PanicStation()
> (2) [1, "two"]

返回类型数组

js.ValueOf() 的文档详细说明了支持的类型及其转换方式:

| Go                     | JavaScript             |
| ---------------------- | ---------------------- |
| js.Value               | [its value]            |
| js.TypedArray          | typed array            |
| js.Func                | function               |
| nil                    | null                   |
| bool                   | boolean                |
| integers and floats    | number                 |
| string                 | string                 |
| []interface{}          | new array              |
| map[string]interface{} | new object             |

请注意,可以 return 一个值,该值将是 JavaScript 中的类型化数组。为此,请使用 js.TypedArray in Go (obtained by js.TypedArrayOf())。支持的类型是:

The supported types are []int8, []int16, []int32, []uint8, []uint16, []uint32, []float32 and []float64. Passing an unsupported value causes a panic.

这是一个如何操作的示例:

func PanicStation(this js.Value, args []js.Value) interface{} {
    return js.TypedArrayOf([]int32{1, 2})
}

这次从 JavaScript 调用 PanicStation(),输出将是:

> PanicStation()
> Int32Array(2) [1, 2]