javascript 如何将 v8 值转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11707167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert v8 Value to Array
提问by david van brink
I'm writing a c++ extension to v8, and want to pass an Array object into it. I see the incoming argument can be tested by IsArray(), but there isn't a ToArray().
我正在为 v8 编写一个 c++ 扩展,并希望将一个 Array 对象传递给它。我看到传入参数可以通过 IsArray() 进行测试,但没有 ToArray()。
How do you get access to its Length, and request elements by numeric index?
你如何访问它的长度,并通过数字索引请求元素?
Handle<Value> MyExtension(const Arguments& args)
{
Handle<Value> v = args[0];
if(v->IsArray())
{
// convert to array, find its length, and access its members by index... ?
}
...
}
Must be missing something obvious here. Object can return all its properties, but that's not quite what I was hoping for. Is there a way to get it as an Arrray?
这里一定遗漏了一些明显的东西。Object 可以返回它的所有属性,但这并不是我所希望的。有没有办法把它作为一个数组?
Thanks for reading.
谢谢阅读。
采纳答案by david van brink
I wasn't able to find a way to convert or cast to Array. Maybe there's a way. But I found by doing object->IsArray()
, object->get("length")->Uint32Value()
, and object->get(int)
, I could just walk the array.
我无法找到转换或强制转换为数组的方法。也许有办法。但我发现通过做object->IsArray()
, object->get("length")->Uint32Value()
, 和object->get(int)
,我可以走阵列。
v8::Handle<v8::Object> obj;
// ... init obj from arguments or wherever ...
int length = 0;
if(obj->IsArray())
{
length = obj->Get(v8::String::New("length"))->ToObject()->Uint32Value();
}
for(int i = 0; i < length; i++)
{
v8::Local<v8::Value> element = obj->Get(i);
// do something with element
}
回答by Vyacheslav Egorov
You should use Cast
method of a handle to cast it to a different type:
您应该使用Cast
句柄的方法将其转换为不同的类型:
v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(v);
回答by clever
i was able to get things working like this, its just a variation of the answer Vyacheslav Egorov gave
我能够让事情像这样工作,这只是 Vyacheslav Egorov 给出的答案的一个变体
Local<Array> arr= Local<Array>::Cast(args[0]);
printf("size %d\n",arr->Length());
Local<Value> item = arr->Get(0);
回答by Jinhyeok Ko
The below is my succeeded code
下面是我成功的代码
v8::Handle<v8::Value> obj(args[0]);
if(obj->IsArray()){
v8::Local<v8::Array> arr= v8::Local<v8::Array>::Cast(args[0]);
v8::String::Utf8Value key(arr->Get(0));
v8::String::Utf8Value value(arr->Get(1));
}