Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The push method cannot be called on the goarray object and errors will be reported #333

Closed
hunjixin opened this issue Jan 17, 2019 · 3 comments

Comments

@hunjixin
Copy link

set a method that return a slice as result to vm, but if i call push method in js ,it will report a type error,
how can i resolve it ?

package main

import (
	"fmt"
	"github.com/robertkrimen/otto"
)
var (
	vm = otto.New()
)

func main(){
	vm.Set("returnarray", returnarray)

	_, err := vm.Run(`
	var arr = returnarray();
	arr.push("test")
`)
	if err != nil {
		fmt.Println(err.Error())
	}
}

func returnarray() otto.Value {
	arrValue,_ :=  vm.ToValue([]string{})
	return arrValue
}
@chrislowth
Copy link

I've had similar challenges with GO arrays converted to JS ones. You need to convert the array to a "TRUE" JS array before "push" and other calls can be made against it. One approach is to "clone" it. This works...

package main

import (
	"fmt"
	"github.com/robertkrimen/otto"
	_ "github.com/robertkrimen/otto/underscore" // ADDED
)
var (
	vm = otto.New()
)

func main(){
	vm.Set("returnarray", returnarray)

	_, err := vm.Run(`
	var arr = returnarray();
	arr = _.clone(arr) // ADDED
	arr.push("test")
`)
	if err != nil {
		fmt.Println(err.Error())
	}
}

func returnarray() otto.Value {
	arrValue,_ :=  vm.ToValue([]string{})
	return arrValue
}

@chrislowth
Copy link

I've done some more research and found the problem (though not solved it)...

A similar problem occurs when trying 'arr[0] = "test"' (though it fails silently) and seems to be because the "setValue" functions in type_go_array.go and type_go_slice.go test that the element already exists before allowing it to be set. This means that you cant change the length an array created in this way.

You can see this by replacing the "push" statement with...

arr[0] = "test"
console.log(arr.length)

Which shows 0 even though the element setting doesnt throw an error

@stevenh
Copy link
Collaborator

stevenh commented Nov 27, 2022

This should be fixed by #460

@stevenh stevenh closed this as completed Nov 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants