瀏覽代碼

Added Runtime.NewArray()

Dmitry Panov 4 年之前
父節點
當前提交
be0895b77e
共有 2 個文件被更改,包括 26 次插入0 次删除
  1. 8 0
      runtime.go
  2. 18 0
      runtime_test.go

+ 8 - 0
runtime.go

@@ -452,6 +452,14 @@ func (r *Runtime) CreateObject(proto *Object) *Object {
 	return r.newBaseObject(proto, classObject).val
 }
 
+func (r *Runtime) NewArray(items ...interface{}) *Object {
+	values := make([]Value, len(items))
+	for i, item := range items {
+		values[i] = r.ToValue(item)
+	}
+	return r.newArrayValues(values)
+}
+
 func (r *Runtime) NewTypeError(args ...interface{}) *Object {
 	msg := ""
 	if len(args) > 0 {

+ 18 - 0
runtime_test.go

@@ -1801,6 +1801,24 @@ func ExampleObject_SetSymbol() {
 	// Output: 1 2 3 4 5 6 7 8 9 10
 }
 
+func ExampleRuntime_NewArray() {
+	vm := New()
+	array := vm.NewArray(1, 2, true)
+	vm.Set("array", array)
+	res, err := vm.RunString(`
+	var acc = "";
+	for (var v of array) {
+		acc += v + " ";
+	}
+	acc;
+	`)
+	if err != nil {
+		panic(err)
+	}
+	fmt.Println(res)
+	// Output: 1 2 true
+}
+
 /*
 func TestArrayConcatSparse(t *testing.T) {
 function foo(a,b,c)