How to convert v8 Value to Array

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

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().

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?

Thanks for reading.

回答1:

You should use Cast method of a handle to cast it to a different type:

v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(v);


回答2:

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.

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 }


回答3:

i was able to get things working like this, its just a variation of the answer Vyacheslav Egorov gave

Local<Array> arr= Local<Array>::Cast(args[0]); printf("size %d\n",arr->Length()); Local<Value> item = arr->Get(0);


回答4:

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));   }


转载请标明出处:How to convert v8 Value to Array
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!