V8:对象数组 [英] v8: Array of objects

查看:201
本文介绍了V8:对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我转化为V8的NodeJS解析器。目前,我有以下结构

I'm transforming a parser for v8 in NodeJS. Currently I have the following structure

struct Node {
    short tag;
    std::string data;

    Node(std::string input, short tagId) {
        tag = tagId;
        data = input;
    }
}; 

std::vector<Node> elems;

和我是从循环填充载体是这样的:

And I'm populating the vector from loop like this:

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

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

My goal is return a javascript object like this:

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

但由于V8文档糟糕,我无法弄清楚如何做到这一点。我最好的拍摄是让

But since the V8 documentation is crappy, I couldn't figure out how to do it. My best shot was to make

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

但我无法弄清楚如何使一个数组并返回它。

but I can't figure out how to make it an array and return it.

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

推荐答案

下面是你可以尝试什么(节点v0.10.x):

Here's what you might try (node 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);

这篇关于V8:对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆