Home >Backend Development >Golang >How to Access a Go Array in Javascript?
In your Golang code, you have an array that you're passing to an HTML file on the front end. You're trying to iterate through the array in Javascript using a for-loop, but the Javascript code fails to load.
It's important to note that template actions like {{index .Array 0}} are executed server-side in Go, while Javascript code runs client-side in the browser. These two environments are separate, so template parameters and values do not exist client-side, and Javascript code cannot execute template actions.
Two options are available:
The {{range}} template action allows you to loop over Array and set the pipeline to the array elements. You can then output the elements like so:
{{range .Array}} {{.}} {{end}}
If you need to process the array in Javascript, you can create a Javascript array using a template like this:
<script> var arr = [ {{range .Array}} {{.}}, {{end}} ]; </script>
Alternatively, you can directly render the array as a Javascript array:
<script> var arr = {{.Array}}; </script>
Now, you have a Javascript array, arr, that you can iterate through and process in Javascript.
The above is the detailed content of How to Access a Go Array in Javascript?. For more information, please follow other related articles on the PHP Chinese website!