v8:对象数组

我正在为NodeJS中的v8转换parsing器。 目前我有以下结构

struct Node { short tag; std::string data; Node(std::string input, short tagId) { tag = tagId; data = input; } }; std::vector<Node> elems; 

而我正在像这样从循环中填充vector:

  elems.push_back(Node(STRING, 3)); 

我的目标是返回一个像这样的javascript对象:

  [ { tag: 2, data: "asdsad" }, { tag: 2, data: "asdsad" }, { tag: 2, data: "asdsad" } ] 

但是,由于V8文档是蹩脚的,我无法弄清楚如何做到这一点。 我最好的select是制作

  Local<Value> data[2] = { Local<Value>::New(Integer::New(2)), String::New("test") }; 

但我不知道如何使它成为一个数组并返回它。

我使用这个例子作为模板。

以下是您可能尝试的内容(节点v0.10.x):

 // in globals static Persistent<String> data_symbol; static Persistent<String> tag_symbol; // in addon initialization function data_symbol = NODE_PSYMBOL("data"); tag_symbol = NODE_PSYMBOL("tag"); // in some function somewhere HandleScope scope; Local<Array> nodes = Array::New(); for (unsigned int i = 0; i < elems.length; ++i) { HandleScope scope; Local<Object> node_obj = Object::New(); node_obj->Set(data_symbol, String::New(elems[i].data.c_str())); node_obj->Set(tag_symbol, Integer::New(elems[i].tag)); nodes->Set(i, node_obj); } return scope.Close(nodes); 

我正在寻找节点5的解决scheme,似乎mscdex的答案已经过时了。 希望这有助于某人。

 HandleScope scope(isolate); Local<Array> nodes = Array::New(isolate); for (unsigned int i = 0; i < elems.length; ++i) { HandleScope scope(isolate); Local<Object> node = Object::New(isolate); node->Set(String::NewFromUtf8(isolate, "data"), String::New(isolate, elems[i].data.c_str())); node->Set(String::NewFromUtf8(isolate, "tag"), Integer::New(isolate, elems[i].tag)); nodes->Set(i, node); } args.GetReturnValue().Set(nodes);