سؤال

In javascriptcore, we can generate an array object using this code:

JSObjectRef array = JSObjectMakeArray(ctx, 0, NULL, NULL)

There're also functions like JSObjectMakeString/JSObjectMakeNumber to generate JSObjectRef objects, so when using an object, I cannot find a method such as JSObjectIsArray to check the object type, but it does have JSValueIsString/JSValueIsNumber method under JSValueRef.

so how to check whether the obj is an array?

هل كانت مفيدة؟

المحلول

To check if an object is an array with JavaScript you can use Array.isArray(obj) (for browsers that support it), like JavaScriptCore implement it, you can write your own JSValueIsArray function, like this :

bool JSValueIsArray(JSContextRef ctx, JSValueRef value)
{
    if (JSValueIsObject(ctx, value))
    {
        JSStringRef name = JSStringCreateWithUTF8CString("Array");

        JSObjectRef array = (JSObjectRef)JSObjectGetProperty(ctx, JSContextGetGlobalObject(ctx), name, NULL);

        JSStringRelease(name);

        name = JSStringCreateWithUTF8CString("isArray");
        JSObjectRef isArray = (JSObjectRef)JSObjectGetProperty(ctx, array, name, NULL);

        JSStringRelease(name);

        JSValueRef retval = JSObjectCallAsFunction(ctx, isArray, NULL, 1, &value, NULL);

        if (JSValueIsBoolean(ctx, retval))
            return JSValueToBoolean(ctx, retval);
    }
    return false;
}

نصائح أخرى

I found some other operations for array, I'd like to paste the code here to help others.

get array length:

int JSArrayGetCount(JSContextRef ctx, JSObjectRef arr)
{
    JSStringRef pname = JSStringCreateWithUTF8CString("length");
    JSValueRef val = JSObjectGetProperty(ctx, arr, pname, NULL);
    JSStringRelease(pname);
    return JSValueToNumber(ctx, val, NULL);
}

get array element by index:

JSValueRef JSArrayGetValueAtIndex(JSContextRef ctx, JSObjectRef arr, int index)
{
    return JSObjectGetPropertyAtIndex(ctx, arr, index, NULL);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top