Search code examples
javascriptcore

How to check if the JSObjectRef object is an array?


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?


Solution

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