You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Go代码中接收JavaScript数组?编译报错求助

Can JavaScript arrays be passed to Go (WebAssembly)?

Yes, you can absolutely pass JavaScript arrays to Go when working with WebAssembly via the syscall/js package. The issue in your code stems from incorrect handling of the JavaScript array values.

What's wrong with your current code?

Your code tries to access Uint8Array directly from the JS array using .Get("Uint8Array"), but regular JavaScript arrays don't have this property. This is why you're getting build or runtime errors. You need to properly convert the JS array elements into a Go slice.

Corrected Code

Here's how to properly receive JS arrays and convert them to Go slices:

func knapsackWrapper() js.Func {
    return js.FuncOf(func(this js.Value, args []js.Value) any {
        // Validate input arguments
        if len(args) < 3 {
            return js.ValueOf("not enough arguments")
        }

        capacity := args[0].Int()
        
        // Convert JS array to Go slice of ints (adjust type as needed)
        weights := jsArrayToIntSlice(args[1])
        values := jsArrayToIntSlice(args[2])

        return Knapsack(capacity, weights, values)
    })
}

// jsArrayToIntSlice converts a JavaScript array to a Go int slice
func jsArrayToIntSlice(arr js.Value) []int {
    length := arr.Get("length").Int()
    slice := make([]int, length)
    for i := 0; i < length; i++ {
        slice[i] = arr.Index(i).Int()
    }
    return slice
}

Key Notes

  • Type Conversion: Use .Index(i) to access elements of the JS array, then convert them to the appropriate Go type (.Int(), .Uint8(), etc.) based on your data.
  • Input Validation: Always check the number of arguments and their types to avoid runtime panics.
  • Typed Arrays: If you're passing a JavaScript typed array (like Uint8Array) instead of a regular array, you can use js.CopyBytesToGo for more efficient conversion:
    func jsUint8ArrayToGoSlice(arr js.Value) []byte {
        byteLength := arr.Get("byteLength").Int()
        slice := make([]byte, byteLength)
        js.CopyBytesToGo(slice, arr)
        return slice
    }
    

Make sure your Knapsack function accepts the correct slice types (e.g., []int or []byte) based on how you convert the JS array.

内容的提问来源于stack exchange,提问作者Rodrigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:05:15