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

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

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

问题

有这样一个Go函数:

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

我将在JavaScript中这样调用它:

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

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

英文:

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>

答案1

得分: 2

这是Go代码从js.Value中提取切片的责任。请参考下面的示例:

func WasmCount(this js.Value, args []js.Value) any {
	if len(args) < 1 {
		fmt.Println("参数数量无效")
		return nil
	}

	arg := args[0]
	if arg.Type() != js.TypeObject {
		fmt.Println("第一个参数应该是一个数组")
		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("索引为%d的项应该是一个字符串\n", i)
			return nil
		}
		firstParam[i] = item.String()
	}

	return len(firstParam)
}

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

func WasmCount(this js.Value, args []js.Value) any {
	if len(args) &lt; 1 {
		fmt.Println(&quot;invalid number of args&quot;)
		return nil
	}

	arg := args[0]
	if arg.Type() != js.TypeObject {
		fmt.Println(&quot;the first argument should be an array&quot;)
		return nil
	}

	firstParam := make([]string, arg.Length())
	for i := 0; i &lt; len(firstParam); i++ {
		item := arg.Index(i)
		if item.Type() != js.TypeString {
			fmt.Printf(&quot;the item at index %d should be a string\n&quot;, i)
			return nil
		}
		firstParam[i] = item.String()
	}

	return len(firstParam)
}

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:

确定