Subj : Re: Iterating through all Array elements from C To : netscape.public.mozilla.jseng From : Matthew Mondor Date : Sat Feb 12 2005 02:23 pm On Thu, 10 Feb 2005 10:41:10 -0500 Matthew Mondor wrote: > Using SpiderMonkey, I have a static function of a class which requires > an array as a parameter. I can get the parameter, verify that it is > indeed an Array... However, I seem to have trouble to iterate though > all its elements, if the indexes are either non-contiguous or > non-numeric at initialization: I could make it work, creating an iterator function as follows. Unfortunately, I had to use JS_Enumerate() with an JSIdArray, which seems to be marked as being private API according to the reference docs. At least it solved my problem for now. If this message ever comes up with a duplicate, my apologies, it seems that the previous message never made it, probably because the function was provided in an attachment, although it was ASCII 7-bit text/plain (not base64 encoded). static JSBool object_iterate(JSContext *, JSObject *, void *, JSBool (*)(JSContext *, jsval *, jsval *, void *)); /* * Was written to be able to iterate over all elements of an array object, * despite being an associated array or not, or a mix of both. Unfortunately * uses marked as private JSIdArray structure. */ static JSBool object_iterate(JSContext *cx, JSObject *obj, void *udata, JSBool (*func)(JSContext *, jsval *, jsval *, void *)) { JSIdArray *a; jsval id, val; char *name; jsint i; JSBool ret = JS_FALSE; if ((a = JS_Enumerate(cx, obj)) != NULL) { for (i = 0; i < a->length; i++) { JS_IdToValue(cx, a->vector[i], &id); if (JSVAL_IS_STRING(id)) { /* * Property id is a string, attempt to * lookup its value by name. */ name = JS_GetStringBytes(JSVAL_TO_STRING(id)); if (!JS_LookupProperty(cx, obj, name, &val)) continue; } else { /* * Property id is a number, attempt to * lookup its array element by index. */ if (!JS_LookupElement(cx, obj, JSVAL_TO_INT(id), &val)) continue; } if (!(ret = func(cx, &id, &val, udata))) break; } JS_DestroyIdArray(cx, a); } return ret; } Matt .